How to Add Property to an Object in JavaScript

Objects in JavaScript are composite data types. It contains Numbers, Strings, Array, or other Objects. An object’s main building blocks are its fields or properties. The property consists of keys and values. A property can be described as a color of a dress, the height of a man, or a person’s address.

After creating an Object, you can either add a new property or change an existing property using numerous methods. Let’s see different ways to add a new property to a JavaScript object.

Javascript add a property to object.

To add a property to an object in JavaScript, use the dot(.) operator. The dot operator grants access to the data inside the object. The dot (.) is just like a plus(+) and minus(-) operator. The variables stored in an object that we access via the dot operator are generically called properties.

To create an Object in JavaScript, use the { }(Curly braces) and add a key: value pair in it. The Object in JavaScript is a collection of named values.

const obj = {
 movie: "Black Widow",
 actor: "Scarlett Johansson"
}

This is an object that has two properties. Let’s add a new property using the dot(.) operator.

const obj = {
 movie: "Black Widow",
 actor: "Scarlett Johansson"
}

console.log(obj)
console.log("After adding a new property")

obj.supporting_actor = "David Harbour"

console.log(obj)

Output

{ 
  movie: 'Black Widow', 
  actor: 'Scarlett Johansson' 
}

After adding a new property

{
  movie: 'Black Widow',
  actor: 'Scarlett Johansson',
  supporting_actor: 'David Harbour'
}

As you can see from the output that we added a new property supporting_actor.

Adding a property to an Object using square brackets

You can also add a property to an Object using square brackets([ ]). The use of square brackets([ ]) provides an excellent way to use the actual value of variables as a key/property while creating JavaScript objects.

const obj = {
 movie: "Black Widow",
 actor: "Scarlett Johansson"
}

console.log(obj)
console.log("After adding a new property using [ ]")

obj["supporting_actor"] = "David Harbour"

console.log(obj)

Output

{ 
   movie: 'Black Widow', 
   actor: 'Scarlett Johansson' 
}

After adding a new property using [ ]

{
  movie: 'Black Widow',
  actor: 'Scarlett Johansson',
  supporting_actor: 'David Harbour'
}

You can get the same output as dot notation. The square brackets([ ]) is the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax.

It’s a shorthand for the object[key] assignment that you know from ES3/5.

That’s it for this tutorial.

Leave a Comment