JavaScript Object Methods
14 April 2025 | Category: JavaScript
In JavaScript, object methods are functions that are stored as properties within an object. They allow objects to perform actions or operations using their own data.
🔍 What Is an Object Method?
A method is just a function defined inside an object.
Example:
const user = {
name: "Alice",
greet: function () {
console.log(`Hello, my name is ${this.name}`);
}
};
user.greet(); // Output: Hello, my name is Alice
greet
is a method of theuser
object.this.name
refers to thename
property of the same object.
đź§ Defining Methods (Shorthand Syntax)
You can define object methods using shorthand syntax:
const user = {
name: "Bob",
greet() {
console.log(`Hi, I'm ${this.name}`);
}
};
This is cleaner and more commonly used in modern JavaScript.
đź§© Built-in Object Methods
JavaScript provides several built-in methods to work with objects:
Object.keys()
Returns an array of keys in an object.
Object.keys({ a: 1, b: 2 }); // ["a", "b"]
Object.values()
Returns an array of values in an object.
Object.values({ a: 1, b: 2 }); // [1, 2]
Object.entries()
Returns an array of key-value pairs.
Object.entries({ a: 1, b: 2 }); // [["a", 1], ["b", 2]]
Object.assign()
Copies properties from one object to another.
const obj1 = { a: 1 };
const obj2 = { b: 2 };
Object.assign(obj1, obj2); // { a: 1, b: 2 }
Object.hasOwnProperty()
Checks if an object has a specific property.
const user = { name: "Tom" };
user.hasOwnProperty("name"); // true
⚙️ Custom Methods with this
The this
keyword refers to the object the method belongs to. It allows methods to work dynamically with the object’s own properties.
Example:
const car = {
brand: "Tesla",
model: "Model 3",
details() {
return `${this.brand} - ${this.model}`;
}
};
console.log(car.details()); // Tesla - Model 3
đź’ˇ Reusable Methods via Prototypes
You can define methods on prototypes so they’re shared across all instances:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound`);
};
const dog = new Animal("Buddy");
dog.speak(); // Buddy makes a sound
đź§Ľ Best Practices
- Use shorthand syntax for cleaner code
- Use
this
wisely — especially in arrow functions (this
behaves differently) - Define reusable methods on prototypes or in classes
- Avoid defining large functions inside every object — use composition or class-based design