How to add a property to a JavaScript object.

This is a tutorial on how to add new properties to a JavaScript object. In this guide, I will also show you how to dynamically set a new property.

Take a look at the following object:

As you can see, the JavaScript object above represents a person. Currently, it has three properties: name, dob and height.

However, what if we wanted to add a new object property that represents that person’s hometown?

In the snippet above, we used dot notation to set a new property called “hometown”.  Dot notation can also be used to overwrite an existing property. For example, if we wanted to change the name of the person, we could do something like this:

Here, we were able to overwrite the value of the name property.

Dynamically setting a new property with JavaScript.

In certain cases, you might not be able manually specific the property name like we did in the examples above. Thankfully, there is an easy way around this:

In the code above, we wrapped the variable containing our dynamic property name in brackets. This tells JavaScript to evaluate the string in our variable and use it as the property name.

If you fail to use the brackets, JavaScript will set the new name as “propertyName”. i.e. It will take it literally.

Using spaces or hyphens in a property name.

If you attempt to use a space or a hyphen in your property name while using regular dot notation, you might end up with an error such as:

Uncaught SyntaxError: Invalid left-hand side in assignment

The error above occurred because I tried to use a hyphen like so:

If you attempt to use a space in the property name, you will probably get the following error:

Uncaught SyntaxError: Unexpected identifier

In order to use spaces or hyphens in your object property names, you must use the square bracket approach:

By wrapping my new property name in quotes and square brackets, I was able to use a space character.

And that’s it! Hopefully, you found this post to be helpful!

See also: Removing a property from a JavaScript object.

Facebook Comments