JavaScript(JS) JS add key value pair to an object

To add a new key/value pair to a JavaScript object, you can use either dot notation or bracket notation. Here's an example using dot notation:

refer to:‮ditfigi‬ea.com
let myObject = {
  foo: "bar"
};
myObject.newKey = "newValue";
console.log(myObject); // Output: { foo: "bar", newKey: "newValue" }

In the example above, we create an object myObject with one key/value pair { foo: "bar" }. We then use dot notation to add a new key/value pair { newKey: "newValue" } to the object. The resulting object is { foo: "bar", newKey: "newValue" }.

You can also use bracket notation to add a new key/value pair to an object:

let myObject = {
  foo: "bar"
};
myObject["newKey"] = "newValue";
console.log(myObject); // Output: { foo: "bar", newKey: "newValue" }

In the example above, we use bracket notation to add a new key/value pair { newKey: "newValue" } to the object myObject. The resulting object is { foo: "bar", newKey: "newValue" }.

Note that if the object already has a key with the same name, the value of that key will be overwritten with the new value.