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 properties values.
const foods = { burger: '🍔', pizza: '🍕' };
// Dot Notation
console.log(foods.burger); // 🍔
// Square Bracket Notation
console.log(foods['pizza']); // 🍕
To add a new key-value pair to an object, the simplest and popular way is to use the dot notation:
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, take a look at this article.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.