How to Add a Key Value Pair to a Javascript Object?

javascript

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'.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?