Object Methods
Learn how to add functions to objects, use the this keyword, and work with built-in Object methods.
Object Methods
An object can hold any type of value — including functions. When a function lives inside an object, it is called a method.
const user = {
name: "Ali",
greet: function() {
console.log("Hello, I am Ali!");
}
};
user.greet(); // Hello, I am Ali!You call a method the same way you access any property — dot notation followed by ().
Methods are what make objects feel alive. Instead of just holding data, an object can also do things with that data.
Method Shorthand
ES6 introduced a cleaner way to write methods — without the function keyword.
// Old way
const user = {
name: "Ali",
greet: function() {
console.log("Hello!");
}
};
// Modern shorthand
const user = {
name: "Ali",
greet() {
console.log("Hello!");
}
};Same behavior, cleaner syntax. The shorthand version is what you will see in most modern JavaScript code.
The this Keyword
A method usually needs to access other properties of its own object. That is what this is for. Inside a method, this refers to the object the method belongs to.
const user = {
name: "Ali",
age: 22,
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
user.greet(); // Hello, my name is Ali and I am 22 years old.this.name reaches into the same object and gets "Ali". Without this you would have no way to access the object's own properties from inside a method.
this always refers to the calling object
Whatever object is to the left of the dot when you call the method — that is what this refers to.
const user1 = {
name: "Ali",
greet() {
console.log(`Hello from ${this.name}`);
}
};
const user2 = {
name: "Sara",
greet() {
console.log(`Hello from ${this.name}`);
}
};
user1.greet(); // Hello from Ali
user2.greet(); // Hello from SaraSame method logic, two different objects. this picks up the right name each time based on which object called the method.
this and Arrow Functions — The Important Gotcha
Arrow functions do not have their own this. If you use an arrow function as a method, this will not refer to the object — it will refer to the outer scope, which is usually undefined in strict mode or the global object.
const user = {
name: "Ali",
// ❌ Arrow function — this is wrong
greet: () => {
console.log(`Hello, ${this.name}`); // undefined
},
// ✅ Regular function — this works correctly
greetCorrect() {
console.log(`Hello, ${this.name}`); // Ali
}
};
user.greet(); // Hello, undefined
user.greetCorrect(); // Hello, AliAlways use regular functions or method shorthand for object methods — never arrow functions.
Arrow functions inherit this from where they were defined — not from where they were called. This makes them wrong for object methods but perfect for callbacks inside methods. We cover this in the Advanced section under the this keyword topic.
Methods That Use and Update Data
Methods can read and update the object's own properties through this.
const counter = {
count: 0,
increment() {
this.count++;
},
decrement() {
this.count--;
},
reset() {
this.count = 0;
},
getCount() {
return this.count;
}
};
counter.increment();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 3
counter.decrement();
console.log(counter.getCount()); // 2
counter.reset();
console.log(counter.getCount()); // 0The object holds its own state (count) and its own behavior (increment, decrement, reset). This is the foundation of how objects work in real applications.
Method Chaining
When a method returns this, you can chain multiple method calls together on one line.
const cart = {
items: [],
add(item) {
this.items.push(item);
return this; // return this enables chaining
},
remove(item) {
this.items = this.items.filter(i => i !== item);
return this;
},
clear() {
this.items = [];
return this;
},
summary() {
console.log(`Cart has ${this.items.length} item(s): ${this.items.join(", ")}`);
return this;
}
};
cart
.add("Laptop")
.add("Mouse")
.add("Keyboard")
.summary()
.remove("Mouse")
.summary();
// Cart has 3 item(s): Laptop, Mouse, Keyboard
// Cart has 2 item(s): Laptop, KeyboardEach method returns this — the same object — so the next method call picks up right where the last one left off. You will see this pattern in libraries like jQuery and many modern APIs.
Built-in Object Methods
JavaScript provides static methods on the Object constructor for common operations. You already saw some in the basics topic — here they are in full.
Object.keys() — get all keys
const user = { name: "Ali", age: 22, city: "Lahore" };
console.log(Object.keys(user));
// ["name", "age", "city"]Object.values() — get all values
console.log(Object.values(user));
// ["Ali", 22, "Lahore"]Object.entries() — get key-value pairs
console.log(Object.entries(user));
// [["name", "Ali"], ["age", 22], ["city", "Lahore"]]Object.assign() — copy or merge objects
Copies properties from one or more source objects into a target object.
const target = { a: 1 };
const source = { b: 2, c: 3 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }Merge multiple objects into a new one:
const defaults = { theme: "light", language: "en", fontSize: 14 };
const userSettings = { theme: "dark", fontSize: 16 };
const settings = Object.assign({}, defaults, userSettings);
console.log(settings);
// { theme: "dark", language: "en", fontSize: 16 }Properties from later sources overwrite earlier ones. userSettings.theme overwrites defaults.theme.
Object.freeze() — prevent all changes
Freezes an object — no properties can be added, removed, or changed.
const config = Object.freeze({
apiUrl: "https://api.example.com",
timeout: 5000
});
config.timeout = 9000; // silently fails in normal mode
console.log(config.timeout); // 5000 — unchangedUseful for constants and configuration objects that should never change.
Object.fromEntries() — build object from entries
The opposite of Object.entries() — takes an array of key-value pairs and builds an object.
const entries = [["name", "Ali"], ["age", 22], ["city", "Lahore"]];
const user = Object.fromEntries(entries);
console.log(user); // { name: "Ali", age: 22, city: "Lahore" }Real use — transforming object values with map() then converting back:
const prices = { laptop: 120000, mouse: 1500, keyboard: 4500 };
// Apply 10% discount to all prices
const discounted = Object.fromEntries(
Object.entries(prices).map(([key, value]) => [key, value * 0.9])
);
console.log(discounted);
// { laptop: 108000, mouse: 1350, keyboard: 4050 }Object.hasOwn() — modern property check
A modern replacement for hasOwnProperty() — cleaner and more reliable.
const user = { name: "Ali", age: 22 };
console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "city")); // falseA Real Example — Bank Account
const account = {
owner: "Ali",
balance: 10000,
deposit(amount) {
if (amount <= 0) {
console.log("Deposit amount must be positive.");
return this;
}
this.balance += amount;
console.log(`Deposited Rs. ${amount}. New balance: Rs. ${this.balance}`);
return this;
},
withdraw(amount) {
if (amount > this.balance) {
console.log("Insufficient funds.");
return this;
}
this.balance -= amount;
console.log(`Withdrew Rs. ${amount}. New balance: Rs. ${this.balance}`);
return this;
},
statement() {
console.log(`Account owner: ${this.owner}`);
console.log(`Current balance: Rs. ${this.balance}`);
return this;
}
};
account
.deposit(5000)
.withdraw(3000)
.deposit(1000)
.statement();
// Deposited Rs. 5000. New balance: Rs. 15000
// Withdrew Rs. 3000. New balance: Rs. 12000
// Deposited Rs. 1000. New balance: Rs. 13000
// Account owner: Ali
// Current balance: Rs. 13000Summary
- A method is a function stored as a property of an object
- Use method shorthand —
greet() {}instead ofgreet: function() {} thisinside a method refers to the object that called it- Never use arrow functions as object methods — they do not have their own
this - Return
thisfrom methods to enable method chaining - Built-in Object methods —
Object.keys(),Object.values(),Object.entries(),Object.assign(),Object.freeze(),Object.fromEntries(),Object.hasOwn() Object.freeze()makes an object completely immutableObject.fromEntries()is the reverse ofObject.entries()— useful for transforming objects through array methods