Skip to main content Accessibility Feedback

Adding items to an object with vanilla JavaScript

Yesterday we looked at how to add items an array with vanilla JavaScript. Today, you’ll learn how to add items to an object.

There are two ways to add items to an object:

  1. Dot notation (obj.something)
  2. Bracket notation (obj['something'])

Dot notation is the generally preferred way, but if you’re using a key set by a variable, or your key has spaces, you need to use bracket notation.

var lunch = {
    sandwich: 'turkey',
    chips: 'cape cod',
    drink: 'soda'
};

// Add items to the object
lunch.alcohol = false;
lunch["dessert"] = 'cookies';

// returns {sandwich: "turkey", chips: "cape cod", drink: "soda", alcohol: false, dessert: "cookies"}
console.log(lunch);

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips