Skip to main content

Command Palette

Search for a command to run...

Objects in JavaScript.

Updated
2 min read

In real-world applications, data is rarely stored as single values. Most of the time, we need to store related information together. For example, if we want to store information about a person, we might need name , age , city etc. Instead of creating separate variables for each value, JavaScript allows us to group them together using objects.

What are Objects?

An object is a data structure used to store multiple related values.Objects store data in key–value pairs.

Example:

{ key: value }

Think of it like a profile card.

Example:

const person = { name: "Hammad", age: 22, city: "Multan" };

Here the keys are name , age and city and vlues are the Hammad , 22 , Multan. Each key represents a property, and each property has a value.

Why Objects are needed:

Imagine storing this data without objects:

const name = "Hammad"; const age = 22; const city = "Multan";

Now suppose you want to store data for 10 people.
Managing separate variables becomes messy.

Objects allow us to group related data together:

const person = { name: "Hammad", age: 22, city: "Multan" };

This makes code organized and easier to manage.

Array vs Object:

Both arrays and objects store multiple values, but they work differently.

Array : Stores values using indexes.

const fruits = ["Apple", "Banana", "Mango"];

Accessing values: console.log(fruits[0]);

Output: Apple

Object : Stores values using keys.

const person = { name: "Ali", age: 25 };

Accessing values: console.log(person.name);

Output: Ali

Creating Objects: We create objects using curly braces {}.

Example:

const person = { name: "Hammad", age: 22, city: "Multan" };

Each property is written as: key: value

Properties are separated by commas.

Accessing Object Properties:

There are two ways to access object properties.

  1. Dot Notation: This is the most common method. console.log(person.name); console.log(person.age); Output : Hammad 22

  2. Bracket Notation: We can also use square brackets. console.log(person["city"]); Output : Multan. Bracket notation is useful when the property name is stored in a variable. Example : const key = "name";

    console.log(person[key]);

output : Hammad

Diagram :