FrontendDeveloper.in

JavaScript question detail

How do you add a key value pair in javascript

There are two possible solutions to add new properties to an object.

Let's take a simple object to explain these solutions.

var object = {
key1: value1,
key2: value2,
};
  1. Using dot notation: This solution is useful when you know the name of the property
object.key3 = "value3";
  1. Using square bracket notation: This solution is useful when the name of the property is dynamically determined or the key's name is non-JS like "user-name"
obj["key3"] = "value3";
Back to all JavaScript questions
Get LinkedIn Premium at Rs 399