This post will discuss how to add a property to an object in JavaScript.

1. Using dot notation

A simple approach is to use the dot notation with an assignment operator to add a property to an existing object. The syntax is: object.property = value.

Download  Run Code

2. Using bracket notation

The dot notation won’t work when the property’s name is not known in advance or the name is an invalid variable identifier (say all digits).

To handle these cases, one can think of an object as an associative array and use the bracket notation. The syntax is: object['property'] = value.

Download  Run Code

 
Note that both the dot notation and bracket notation will overwrite the object’s property with the given property when the specified key is already found in the object. To illustrate, consider the following code, which overwrites the age property of the person object.

Download  Run Code

3. Using Object.assign() function

The Object.assign() method can copy properties from a source object to a target object. Properties in the sources overwrite the target object’s properties if the same key is found in both objects.

Download  Run Code

4. Using Spread operator

Alternatively, you can use the Spread operator to merge the properties of two objects into a new object. This approach does not overwrite the source object with the properties of the given object for common keys.

Download  Run Code

5. Using jQuery

With jQuery, you can use the jQuery.extend() method, which merges the contents of the second object into the first object. If objects have keys in common, this approach overwrites the source object with the given object’s properties.

Download Code

6. Using Underscore/Lodash Library

Both Underscore and Lodash libraries offer several utility methods to add properties to an existing object.

With the Lodash library, you can use any of the _.merge, _.assignIn (alias _.extend), _.assign, or _.defaults method. Alternatively, if you prefer the Underscore library, you can use the _.extendOwn (Alias: _.assign) or _.defaults method.

All the above-mentioned methods overwrite the source object with the given object’s properties if they have any key in common, except the _.defaults method, which silently ignores the common key.

Download Code

That’s all about adding a property to an object in JavaScript.