Add Key-Value Pair to an Object in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to add key-value pair to an object in JavaScript. For this, we can use dot . notation or square bracket [] notation.

Using dot . notation:

Syntax

object.key = value;

Example 1:  Add Key-Value Pair to an Object Using Dot . Notation

// program to add a key-value pair to an object

const student = {
    name: 'john doe',
    grade : 5,
    gender: 'male'
}

student.hobby = "playing";

console.log(student);

Output

{ 
 name: 'john doe',
 grade: 5, 
 gender: 'male',
 hobby: 'playing'
 }

Using square bracket [] notation

Syntax

object[key] = value;

Example 2: Add Key-Value Pair to an Object Using Square Bracket [] Notation

// program to add a key-value pair to an object

const student = {
    name: 'john doe',
    grade : 5,
    gender: 'male'
}

student["hobby"] = "playing";

console.log(student);

Output

{ 
 name: 'john doe',
 grade: 5, 
 gender: 'male',
 hobby: 'playing'
 }