Skip to content

JavaScript add to object | Example code

  • by

There are two ways to add new properties to an object in JavaScript.

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

Source: stackoverflow.com

JavaScript add to object

Simple example program to add a key/value pair to an object Using Dot Notation.

<!DOCTYPE html>
<html>
<body>
  <script >
    const person = {
      name: 'John',
      age: 25,
      gender: 'M'
    }

    person.height = 7.1;

    console.log(person);
  </script>
</body>
</html>

Output:

JavaScript add to object

Using Square Bracket Notation

<script >
    const person = {
      name: 'John',
      age: 25,
      gender: 'M'
    }

    person['height'] = 5.4;

    console.log(person);
</script>

The spread syntax is useful for combining the properties and methods of objects into a new object:

You can add a property to an object like this

const obj1 = {hello: "🤪"};
const obj2 = {...obj1, laugh: "😂" };
console.log('obj1', obj1)
console.log('obj2', obj2)

Output:


obj1 {
  "hello": "🤪"
}
obj2 {
  "hello": "🤪",
  "laugh": "😂"
}

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading