How to Add a Key Value Pair to a Javascript Object?
To add a key-value pair to a JavaScript object, you can use either dot notation or bracket notation. Here is an example using both:
Using dot notation:
const obj = {
name: 'John',
age: 25
};
obj.city = 'New York';
console.log(obj); // { name: 'John', age: 25, city: 'New York' }
Using bracket notation:
const obj = {
name: 'John',
age: 25
};
obj['city'] = 'New York';
console.log(obj); // { name: 'John', age: 25, city: 'New York' }
In both cases, we simply added a new key-value pair to the object obj
. The key is 'city'
and the value is 'New York'
.