Categories
JavaScript JavaScript Basics

How to Add Property to an Object in Javascript

Spread the love

There’re a few ways to add properties to an object in JavaScript.

One way is to add a property using the dot notation as follows:

obj.foo = 1;

We added the foo property to the obj object above with value 1.

We can also add a property by using the bracket notation as follows:

obj['foo'] = 1;

It does the same thing as the first example, but we can have invalid property identifiers in the string.

So we can write something like:

obj['foo-bar'] = 1;

'foo-bar' isn’t a valid identifier, but we can add it as a property.

We can also use the Object.defineProperty function as follows:

Object.defineProperty(obj, 'foo', {
  value: 1
})

We can have more control of how property will act with this method. In addition to setting the value with the value property, we can also set it to be writable or not with the writable property, and set it to be enumerable or not with the enumerable property.

Enumerable means that whether it’ll be retrieved or looped through with Object.keys or the for-in loop.

Writable means whether we can set a new value for the property.

Setting the property to an object with JavaScript is an easy task if we use these 3 ways to do it.

Leave a Reply

Your email address will not be published. Required fields are marked *