Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Best for beginners who need a clear, structured roadmap.

Updated
3 min read
Understanding Objects in JavaScript

What are Objects?

Objects are one of the 8 data types provided by JavaScript.

It is a non-primitive data type.

It is mutable.

It contains key-value pairs.

Syntax:

{
    key: value,
}

How to create an Object?

By Object Literal

const obj = {};

By Object Constructor

const obj = new Object();

Accessing Properties

Dot Notation

const person = {
    name: "Jaspreet",
    age: 21,
    city: "Mohali",
};

console.log(person.name); // "Jaspreet"

console.log(person.age); // 21

console.log(person.city); // "Mohali"

Dot Notation can only access Valid Identifiers.

What are Valid Identifiers?

  • Do not start with Numbers

  • Do not contain whitespaces

  • Do not use reserved keywords

  • Only starts with letter, $ or _

Bracket Notation

const student = {
    "full name": "Jaspreet Sharma",
    "Number of Subjects": 15,
    course: "B.TECH CSE",
};

console.log(student["full name"]); // "Jaspreet Sharma"

console.log(student["Number of Subjects"]); // 15

console.log(student["course"]); // "B.TECH CSE"

Updating Object Properties

New properties can be created and existing properties can be updated using dot and bracket notation.

const person = {
    name: "Jaspreet",
    age: 21,
    city: "Mohali",
};

person.state = "Punjab";

person["country"] = "India";

person.city = "Muktsar";

console.log(person["state"]); // "Punjab"

console.log(person.country); // "India"

console.log(person.city); // "Muktsar"

Deleting Object Properties

const person = {
    name: "Jaspreet",
    age: 21,
    city: "Mohali",
};

delete person.city;

console.log(person.city); // undefined

Looping Object Keys

There are many ways to loop through object keys. Most common is for in loop.

const person = {
    name: "Jaspreet",
    age: 21,
    city: "Mohali",
};

for(const key in person) console.log(`\({key}: \){person[key]}`);
// "name: Jaspreet"
// "age: 21"
// "city: Mohali"

Object Validation

console.log(typeof {}); // "object"

console.log(typeof []);  // "object"

console.log(typeof null); // "object"

Since typeof returns "object" in the case of object, array and null.

Now the question arises, how do we validate that the data arriving is an object or not?

First of all, we need to check whether it is an object.

typeof data === "object"

Then, we need to check whether the data is null or not.

data === null 

At the end, we need to check whether the data is an Array or not.

Array.isArray(data)

If typeof data is "object", data is not null and data is not an array. Then, we can surely say that data arrived is an Object.

Understanding Objects in JavaScript