How to add a property to an object in JavaScript

To add a new property to a JavaScript object:

  1. You either use the dot (.) notation or the square bracket ([]).
  2. In dot donation, you use the object name followed by the dot, the name of the new property, an equal sign, and the value for the new property.
  3. In square bracket notation, you use the property name as a key in square bracket followed by an equal sign and the value of the new property.

A JavaScript object is a collection of key-value pairs called properties. Unlike arrays, objects don't provide an index to access the properties.

You can either use the dot (.) notation or the square bracket ([]) notation to access property values.

const foods = { burger: '🍔', pizza: '🍕' };

// Dot Notation
console.log(foods.burger); // 🍔

// Square Bracket Notation
console.log(foods['pizza']); // 🍕

The simplest and most popular way is to use the dot notation to add a new key-value pair to an object:

foods.custard = '🍮';

console.log(foods);
// { burger: '🍔', pizza: '🍕', custard: '🍮' }

Alternatively, you could also use the square bracket notation to add a new item:

foods['cake'] = '🍰';

console.log(foods);
// { burger: '🍔', pizza: '🍕', cake: '🍰' }

As you can see above, when you add a new item to an object, it usually gets added at the end of the object.

To learn more about JavaScript objects, prototypes, and classes, read this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.