javascript add a property to an object code example

Example 1: how to add property to object in javascript

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

data["PropertyD"] = 4;

// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);

Example 2: add property to object javascript

let yourObject = {};

//Examples:
//Example 1
let yourKeyVariable = "yourKey";
yourObject[yourKeyVariable] = "yourValue";

//Example 2
yourObject["yourKey"] = "yourValue";

//Example 3
yourObject.yourKey = "yourValue";

Example 3: Add New Properties to a JavaScript Object

var myDog = {
  "name": "Happy Coder",
  "legs": 4,
  "tails": 1,
  "friends": ["freeCodeCamp Campers"]
};

myDog.bark = "woof";
// or
myDog["bark"] = "woof";