Objects in JavaScript can also have methods or functions as properties. Object methods in JavaScript are actions that can be performed by an object.
If you are new to Objects, learn about it on our 👉 JavaScript Objects lesson.
Defining and Calling Object Methods 😎
Object methods in JavaScript can be defined in the same way how we define normal properties i.e. in key: value pairs.
Calling an object method is exactly the same as how we call functions which is by typing the method-name along with parenthesis ( ).
Example
Output
Here, the object Jacky has three properties: name, age and bark. The properties name and age are normal properties whereas bark is an object method defined on the object Jacky.
Example (With Parameters) 👨💻
Output
Example (With Arrow Functions) 🏹
Arrow functions were introduced in the newer version of JavaScript called ES6, which has a cleaner syntax where you don’t even have to type the keyword function to define a function. Hence, arrow functions are a more preferred way to define a function.
Output
JavaScript this keyword 👇
We can access the properties of an object, inside the object itself by using the this keyword.
The this keyword in JavaScript refers to the object, inside which, the keyword itself is called.
Example
Output
Example (With Arrow Function) 🏹
Unfortunately, the above example will return undefined when used on arrow functions.
Output
In this way, object methods in JavaScript help us in performing actions. Here, we defined our own object methods, but JavaScript also provides us with it’s own set of built-in object methods. We will cover that in our next lesson.