Explain JavaScript Object Methods
JavaScript object methods are functions that are stored as object properties. These methods can perform actions using the data contained in the object. Let's go over some common object methods with examples:
1. Creating an Object with Methods
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
},
greet: function() {
return "Hello, " + this.firstName;
}
};
console.log(person.fullName()); // Output: John Doe
console.log(person.greet()); // Output: Hello, John
2. Using this
Keyword
The this
keyword refers to the object that the method is a property of. In the above example, this.firstName
refers to person.firstName
.
3. Adding Methods to an Existing Object
You can also add methods to an object after it has been created:
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
car.getCarInfo = function() {
return this.make + " " + this.model + " (" + this.year + ")";
};
console.log(car.getCarInfo()); // Output: Toyota Corolla (2020)
4. Object Methods with Parameters
Methods can also take parameters:
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(9, 4)); // Output: 5
5. Built-in Object Methods
JavaScript provides several built-in methods for objects. Some of these include:
Object.keys()
Object.values()
Object.entries()
Object.keys()
Returns an array of a given object's own enumerable property names.
const user = {
name: "Alice",
age: 25,
city: "Wonderland"
};
console.log(Object.keys(user)); // Output: ["name", "age", "city"]
Object.values()
Returns an array of a given object's own enumerable property values.
console.log(Object.values(user)); // Output: ["Alice", 25, "Wonderland"]
Object.entries()
Returns an array of a given object's own enumerable property [key, value]
pairs.
console.log(Object.entries(user)); // Output: [["name", "Alice"], ["age", 25], ["city", "Wonderland"]]
6. this
Inside Methods
When a method is called as a property of an object, this
refers to the object itself.
const book = {
title: "1984",
author: "George Orwell",
getSummary: function() {
return `${this.title} by ${this.author}`;
}
};
console.log(book.getSummary()); // Output: 1984 by George Orwell
Conclusion
JavaScript object methods are essential for creating and manipulating objects effectively. They provide a way to bundle related data and behavior, making your code more modular and easier to understand.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.