Skip to main content

Introduction to Methods

A Method is simply a function that has been attached as a property of an Object.

Since essentially everything in JavaScript (aside from true primitives) builds upon Objects, practically all complex data types come with built-in methods designed to manipulate their state.

Defining Custom Methods

You can create methods inside your own objects:

const user = {
name: "Midhun",
age: 25,
// Method declaration
sayHello: function() {
console.log("Hello there!");
},
// Modern ES6 Method Syntax (Preferred)
greet() {
console.log(`Hi, my name is ${this.name}`);
}
};

user.sayHello(); // Hello there!
user.greet(); // Hi, my name is Midhun

The Power of this

Notice the this.name in the greet() method? When you invoke a method, this acts as a reference keyword pointing back to the object executing the current function. It allows methods to access sibling properties natively!

If you called user.greet(), JS evaluates this.name into user.name.