Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to add a property to a JavaScript object using a variable as the name?

  • Last Updated : 17 Aug, 2020

We can create a JavaScript object with an object literal:

Example :

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

 var obj = { firstname : "Romy", lastname : "kumari", age : 20}

The name: values pairs in JavaScript objects are called properties. We can add the property to JavaScript object using a variable as the name by using dot notation or bracket notation.

Below example illustrate explain two different approaches:



Example 1: In this example, we will be using dot notation.

HTML




<!DOCTYPE html>
<html>
    <body>
        <p style="font-size: 30px; color: green;" ;>
          GeeksforGeeks
        </p>
  
  
        <p id="add"></p>
  
  
        <script>
            // Variable a and b
            var a = "string1";
            var b = "string2";
            var object1 = { firstname: "Romy", 
                            lastname: "Kumari" };
  
            // Property using variable name
            object1.a = "first property";
            object1.b = "Second Property";
  
            document.getElementById("add").innerHTML = 
              "Added peoperty are : " + object1.a + 
              " and " + object1.b;
        </script>
    </body>
</html>

Output:

Example 2: We can use the bracket operator if we want to add the property with the value stored in the variable. The obj.a is not same as obj[a]

HTML




<!DOCTYPE html>
<html>
    <body>
        <p style="font-size: 30px; color: green;";>
          GeeksforGeeks
        </p>
  
  
        <p id="add"></p>
  
  
        <script>
            var myObj = new Object();
  
            var a = "string1";
            var b = "string2";
            // This can be accesses with
            // the value stored in b.
            myObj.b = "somewhere";
            // This can be accessed with the 
            // value stored in a that is string1
            myObj[a] = "whatever"; 
  
            document.getElementById("add").innerHTML = 
              "Added peoperty are : " + myObj.string1 +
              " and " + myObj.b;
        </script>
    </body>
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :