How can I add Key/Value pair to Object

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

There are two ways to add new properties to an object

Method 1 – Using dot notation

 obj.key3 = "value3";

Method 2 – 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");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Comments are closed.