Sunday, January 07, 2018

Adding a New Property to an Object

In Javascript, you can add new properties to an object using dot notation or square bracket notation.

var myObject = {
      key1: "val1",
      key2: "val2",
      key3: "val3"
};

DOT NOTATION:

myObject.key4 = "val4";

Object { key1: "val1", key2: "val2", key3: "val3", key4: "val4" }

SQUARE BRACKET NOTATION:

With square brackets, it'll want the key name as a string.

myObject["key5"] = "val5";

Object { key1: "val1", key2: "val2", key3: "val3", key4: "val4", key5: "val5" }

Image Credit: Spot the Skylab by NASA at nasa.gov

Post a Comment

Note: Only a member of this blog may post a comment.