JS Coding Questions Logo
JS Coding Questions
#136💼 Interview💻 Code

How do you add a key value pair in javascript

Advertisement

728x90

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

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

javascript
1var object = {
2  key1: value1,
3  key2: value2,
4  };

1. Using dot notation: This solution is useful when you know the name of the property

javascript
1object.key3 = "value3";

2. 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"

javascript
1obj["key3"] = "value3";

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 52

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
136of476