Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
JavaScript Program to Add Key/Value Pair to an Object
In this example, you will learn to write a JavaScript program that will add a key/value pair to an object.
To understand this example, you should have the knowledge of the following JavaScript programming topics:
Example 1: Add Key/Value Pair to an Object Using Dot Notation
// program to add a key/value pair to an object
const person = {
name: 'Monica',
age: 22,
gender: 'female'
}
// add a key/value pair
person.height = 5.4;
console.log(person);
Output
{
name: "Monica",
age: 22,
gender: "female",
height: 5.4
}
In the above example, we add the new property height to the person object using the dot notation . i.e. person.height = 5.4;.
Example 2: Add Key/Value Pair to an Object Using Square Bracket Notation
// program to add a key/value pair to an object
const person = {
name: 'Monica',
age: 22,
gender: 'female'
}
// add a key/value pair
person['height'] = 5.4;
console.log(person);
Output
{
name: "Monica",
age: 22,
gender: "female",
height: 5.4
}
In the above example, we add the new property height to the person object using the square bracket notation [] i.e. person['height'] = 5.4;.
Also Read:
Did you find this article helpful?