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, we will also show you how to dynamically set a new property.

Take a look at the following object:

//Basic JavaScript object that represents a person.
var person = {
    name: 'Michael Jordan',
    dob: '1963-02-17',
    height: 1.98
}

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

What if we wanted to add a new object property representing that person’s hometown?

//Setting a new property using dot syntax.
person.hometown = 'Wilmington, North Carolina';

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:

//Overwriting an object property.
person.name = 'LeBron James';

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 to manually specify the property name like we did in the examples above.

Thankfully, there is an easy way around this:

//Dynamically setting properties
var propertyName = 'new_property';

//Use square brackets
person[propertyName] = 'Test';

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”.

In other words, 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:

//This will cause a SyntaxError
person.name-test = 'LeBron James';

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:

//Using a space in a property name.
person["name test"] = 'LeBron James';

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

See also: Removing a property from a JavaScript object.