This post will describe the methods for adding elements to a JavaScript object.
How to Add Elements to Objects in JavaScript?
To add elements to an object, use the following approaches:
Method 1: Adding Elements to Object Using the Dot(.) Operator
For adding elements in an object utilizes the “Dot” notation. It is used for accessing, adding or modifying the properties and methods of objects. The dot operator is a fundamental feature of JavaScript and is used extensively in object-oriented programming.
Syntax
Use the below-provided syntax for adding elements to an object using the (.) notation:
Example
Create an empty object named “stdInfo”:
Add some elements in a key-value pair with the help of dot notation:
stdInfo.name = "Mari";
After adding elements, print the object on the console:
As you can see that the elements have been successfully added to an empty object:
Method 2: Adding Elements to Object Using the Square Bracket Notation [ ]
You can also use the “square bracket” notation for adding the elements to the object. Similar to dot notation, it is also utilized for accessing, adding, and modifying object properties and methods.
Syntax
For adding elements using [ ] notation, follow the given syntax:
Example
Add the “age” of the student to the object using the bracket [ ] notation:
Output
Method 3: Adding Elements to Object Using assign() Method
Another way to add elements to an object is to use the “assign()” method. It is utilized to copy the values of all enumerable properties from multiple source objects to a specified target object.
Syntax
The general syntax for the assign() method is as follows:
For adding elements to an object, use the given syntax:
Here, the “object” is the target.
Example
Let’s add a property “standard” in an object utilizing the assign() method:
It can be observed that the assign() method successfully added the key-value pair to an object:
We have provided all the essential instructions relevant to adding elements to the object.
Conclusion
For adding elements to an object, use the “Dot (.)” operator, “Square bracket [ ]” notation, or the “assign()” method. The dot operator and the square bracket notation are the most common approaches utilized for accessing or adding properties to an object. This post described the methods for adding elements to an object in JavaScript.