Object Methods
Learn how JavaScript objects can contain functions as methods and how those methods can perform actions using the data stored inside an object.
What are Object Methods?
A JavaScript object can contain properties and functions. When a function is stored as a property of an object, that function is called a method.
Methods describe the actions or behaviour that an object can perform.
Property vs Method
A property stores information, such as a course name or duration.
A method stores a function that performs an action related to that object.
JavaScript object method: a function stored as an object property and called using object.method().
Object Method Syntax
A method can be created by assigning a function to an object property.
let course = {
name: "JavaScript",
showCourse: function () {
console.log("Course: JavaScript");
}
};
course.showCourse();
Parts of an Object Method
Object
The object that contains properties and methods.
Method Name
The name used to identify and call the method.
Function Body
Contains the statements executed when the method is called.
The method is accessed using objectName.methodName(). Parentheses execute the function stored in the method.
Example 1: Creating an Object Method
Here, the showCourse() method performs an action when it is called.
let course = {
title: "JavaScript",
duration: "3 Months",
showDetails: function () {
console.log(this.title);
console.log(this.duration);
}
};
course.showDetails();
Output: 3 Months
Example 2: Method with Parameters
An object method can accept parameters just like a normal JavaScript function.
let calculator = {
add: function (first, second) {
return first + second;
}
};
console.log(calculator.add(15, 25));
Example 3: Multiple Methods
One object can contain multiple methods. Each method can perform a different operation.
let trainer = {
startClass: function () {
return "Class Started";
},
endClass: function () {
return "Class Completed";
}
};
console.log(trainer.startClass());
console.log(trainer.endClass());
Output: Class Completed
Example 4: Method Using Object Properties
A method can use properties belonging to the same object. The this keyword is commonly used for this purpose.
let student = {
name: "Priya",
course: "JavaScript",
getDetails: function () {
return this.name + " is learning " + this.course;
}
};
console.log(student.getDetails());
Important
To execute an object method, use parentheses after the method name.
Example: student.getDetails()
The next topic, this Keyword, will explain in detail how this refers to the current object inside an object method.
Summary
An object method is a function stored as a property of an object. Methods allow objects to perform actions, accept parameters, return values, and work with the object's own properties. Methods are called using the syntax objectName.methodName().