Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In JavaScript, there are several ways to add and modify object properties and methods. The choice of method depends on your specific requirements and coding style. Here are common ways to add or modify properties and methods of an object:
You can add or modify an object property using dot notation.
javascriptconst person = { name: "John" };
person.age = 30; // Adding a new property
person.name = "Jane"; // Modifying an existing property
You can add or modify an object property using "bracket notation". This is useful when the property name is dynamic or contains special characters.
javascriptconst person = { name: "John" };
person["age"] = 30; // Adding a new property
person["first name"] = "Jane"; // Modifying an existing property with a special character in the name
You can use Object.defineProperty()
to add or modify properties with additional attributes like configurability and writability.
javascriptconst person = {};
Object.defineProperty(person, "name", {
value: "John",
writable: true,
configurable: true,
enumerable: true,
});
You can add a method to an object by declaring a function within the object literal.
javascriptconst person = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
},
};
In modern JavaScript (ES6 and later), you can use the method shorthand notation to define methods.
javascriptconst person = {
name: "John",
greet() { // Function keyword removed here
console.log(`Hello, my name is ${this.name}.`);
},
};
You can use Object.assign()
to copy properties and methods from one object to another.
javascriptconst person = { name: "John" };
const additionalInfo = {
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}.`);
},
};
Object.assign(person, additionalInfo); // Adding properties and methods
For constructor functions, you can add or modify methods on the prototype chain, affecting all instances of the object.
javascriptfunction Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}.`);
};
These methods allow you to add or modify properties and methods of objects in various ways, catering to your specific needs and coding style. Depending on your use case, choose the method that suits you best.