You can simply use the dot notation (.) to add a key/value pair or a property to a JavaScript object.
Let's try out the following example to understand how it basically works:
// Sample object
var myCar = {
make: "Ferrari",
model: "Portofino",
year: 2018
};
// Adding a new property
myCar.fuel = "Petrol";
console.log(myCar);
Alternatively, you can also use the square bracket notation ([]) to add a key/value pair to a JavaScript object. The following example produces the same result as the previous example:
The advantage of using square bracket notation is, you can substitute the key inside the square bracket with a variable to dynamically assign a key or property name to an object.
// Sample object
var myCar = {
make: "Ferrari",
model: "Portofino",
year: 2018
};
// Sample variables
var myKey = "fuel";
var myValue = "Petrol";
// Dynamically adding a key/value pair
myCar[myKey] = myValue;
console.log(myCar);
Use Dot Notation or Square Bracket
You can simply use the dot notation (
.) to add a key/value pair or a property to a JavaScript object.Let's try out the following example to understand how it basically works:
Alternatively, you can also use the square bracket notation ([]) to add a key/value pair to a JavaScript object. The following example produces the same result as the previous example:
The advantage of using square bracket notation is, you can substitute the key inside the square bracket with a variable to dynamically assign a key or property name to an object.
need an explanation for this answer? contact us directly to get an explanation for this answer