To add a new property to a JavaScript object:
- You either use the dot (
.) notation or the square bracket ([]). - 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.
- 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.