How to Add a Property to the JavaScript Object?

Objects in JavaScript are like the backbone of a human being. Without objects, JavaScript is nothing.

JavaScript object is a collection of unordered properties. JavaScript Object properties are nothing but the values associated with the JavaScript object. Properties can usually be added, changed, and deleted. They are the most crucial part of any JavaScript object.

We can add a new property to an existing JavaScript object by simply providing a value to it. There are two ways to add properties to JS objects.

Method 1

First, let’s create a new empty object in JavaScript.

let codingLevels = {};
console.log(codingLevels); // Object {  }

Now, add a new property to an existing object codingLevels. We can do it easily by setting an object key and assigning a value for the key.

codingLevels['Python'] = "Easy"; // here, "Python" is the key and "Easy" is the value

Now, log the object to confirm that the new property is added.

console.log(codingLevels); // Object { Python: "Easy" }

Method 2

Let’s add another property to the existing object codingLevels.

We can add a property using the dot operator. Here is an example to do so.

codingLevels.JavaScript = "Medium";

Now, log the object to the console to verify that the property is added.

console.log(codingLevels); // Object { Python: "Easy", JavaScript: "Medium" }

Now, we can confirm that the second property is added successfully.

We can get the properties of the object by using the same methods we used for adding the properties.

Conclusion

It is really easy to add, change, and delete the JavaScript object properties. You can make use of any one of the two methods to manipulate the object’s properties.