Skip to main content

Command Palette

Search for a command to run...

Understanding Objects in JavaScript

Updated
3 min read

Hey there, in this article we learn about the objects in js, why objects are being used, ohw to loop over the objects, different methods to handle the looping on object keys,values and complete single entry.

What are Objects ?

Objects in JavaScript are a fundamental data type used to store collections of key-value pairs and represent complex entities

Example information about a person:

Name → Rahul
Age → 22
City → Delhi

Instead of storing these values in separate variables, we can group them together inside an object.

Why Do We Need Objects?

Objects help us organize related data in a structured way.

// without object
let name = "Rahul";
let age = 22;
let city = "Delhi";

// with object
let person = {
  name: "Rahul",
  age: 22,
  city: "Delhi"
};

Creating an Object

Objects are created using curly braces {}. Inside the braces, we define key-value pairs.

Syntax

let objectName = {
  key: value
};

Accessing Object Properties

There are two ways to access object properties.

Dot Notation

This is the most common method.

let person = {
  name: "Rahul",
  age: 22,
  city: "Delhi"
};

console.log(person.name); // Rahul
console.log(person.age); // 22

Bracket Notation

Bracket notation uses square brackets.

console.log(person["city"]);

Updating Object Properties

Object values can be updated easily.

let person = {
  name: "Rahul",
  age: 22
};

person.age = 23;

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

Adding New Properties

We can add new properties to an object anytime.

let person = {
  name: "Rahul",
  age: 22
};

person.city = "Mumbai";

console.log(person); // { name: "Rahul", age: 22, city: "Mumbai" }

Deleting Properties

To remove a property, we use the delete keyword.

let person = {
  name: "Rahul",
  age: 22,
  city: "Delhi"
};

delete person.city;

console.log(person); // { name: "Rahul", age: 22 }

Looping Through Object Keys

We can loop through object properties using a for...in loop.

Example

let person = {
  name: "Rahul",
  age: 22,
  city: "Delhi"
};

for (let key in person) {
  console.log(key, person[key]);
} 
// Expected Output--
// name Rahul
// age 22
// city Delhi

Array vs Object

Arrays store ordered collections of values using numeric indices (starting from 0). They are ideal for lists where order matters, such as a sequence of numbers, strings, or objects.

Objects store data as key-value pairs, where keys are typically strings (or symbols) and values can be any data type. They are used to represent entities with properties, like a person, car, or configuration.