Objects in JavaScript

Take out your Aadhaar card or school ID card. 🪪 What do you see?

Name     : Priya Sharma
Age      : 21
City     : Lucknow
Student  : Yes

Every detail has a label (like Name) and a value (like Priya Sharma). All the details belong to one person, so they are printed together on one card.

In JavaScript, we store this kind of information in an object.


What Is an Object?

An object is a collection of related information, stored as key: value pairs, inside curly braces { }.

const student = {
  name: "Priya",   // ← one property
  age: 21          // ← another property
};
TermMeaningExample
Key (property name)The labelname
ValueThe data stored for that label"Priya"
PropertyOne key: value pairname: "Priya"

Key points:

  • An object is written inside curly braces { }.
  • Each property is written as key: value.
  • Properties are separated by commas ,.
  • A value can be any type: a string, number, boolean, array, another object, or even a function.

Array vs Object: What's the Difference?

In the last lessons, we used arrays. So why do we need objects?

Look at this array of a student's details:

const student = ["Priya", 21, "Lucknow", true];

What does 21 mean? Age? Roll number? Marks? 🤔 And what is true? You can't tell by looking at it.

Now the same data as an object:

const student = {
  name: "Priya",
  age: 21,
  city: "Lucknow",
  isStudent: true
};

Now everything is clear, because every value has a label. 🎯

PointArray [ ]Object { }
Stores data asAn ordered listLabelled key: value pairs
Access items byPosition (index): arr[0]Name (key): obj.name
Best forA list of similar thingsDetails of one thing
ExampleA list of citiesOne person's profile

Simple way to remember:

  • Array → a shopping list 📝: many items of the same kind, in order
  • Object → an ID card 🪪: many different details about one thing

Why Use Objects? (Use Cases)

Objects are everywhere in JavaScript. Almost every app you use stores its data in objects.

Real-life thingObject properties
👤 A user profilename, email, phone, isLoggedIn
📱 A product on a shopping sitename, price, brand, inStock
🍕 A food orderorderId, items, total, status
🚆 A train ticketpnr, trainName, seat, date
🏏 A cricket playername, team, runs, wickets
⚙️ App settingstheme, language, notifications

Example: a product on a shopping app 🛒

Benefits of objects

  • Organised: All details about one thing stay together.
  • Readable: Every value has a meaningful name.
  • Easy to access: Get any detail directly by its name, with no need to remember positions.
  • Flexible: Add, change, or remove details at any time.
  • Real-world friendly: They match how we think about things in real life.

Creating Objects

1. Object literal { } (most common ✅)

This is the simplest and most used way.

An empty object is written as { }. You can add properties to it later.

2. Using new Object()

This works, but { } is shorter and cleaner, so developers prefer it.

3. Shorthand properties (a handy shortcut)

If your variable name is the same as the key name, you can write it only once.

What can an object store?

An object can hold any kind of value, even arrays, other objects, and functions.

When a function is stored inside an object, it is called a method. You will learn more about methods in a later lesson.

Rules for keys

  • Keys are usually written like variable names: firstName, price, isActive.
  • If a key has spaces or special characters, put it in quotes:

Accessing Object Properties

There are two ways to read a value from an object.

1. Dot notation . (most common ✅)

Write the object name, a dot, and then the key.

Read it as: "student's name", "student's age". Simple and clean! ✨

2. Bracket notation [ ]

Write the key as a string inside square brackets.

When do we NEED bracket notation?

Dot notation is easier, but in two situations you must use brackets.

Situation 1: The key has spaces or special characters

Situation 2: The key is stored in a variable

Think of it like a locker room 🔐:

  • phone.whatToShow → "Open the locker labelled whatToShow." There is no such locker!
  • phone[whatToShow] → "Open the locker whose name is written on this slip." The slip says "price". ✅

Real example: showing a detail the user picked

Dot vs bracket: quick comparison

PointDot obj.keyBracket obj["key"]
Easy to read✅ YesLess clean
Keys with spaces or -❌ No✅ Yes
Key stored in a variable❌ No✅ Yes
Use itMost of the timeWhen dot notation can't work

Reading a property that doesn't exist

If you ask for a key that isn't there, JavaScript gives undefined, not an error.


Accessing Nested Objects

An object can have another object inside it. To reach a value deep inside, just keep adding dots.

It's like giving directions: "Go to the order, then the customer, then the address, then the city." 🗺️

⚠️ Safe access with optional chaining ?.

What if a nested object doesn't exist? Trying to go deeper gives an error.

?. means: "Only go further if this part exists. Otherwise, just give undefined."

You can also give a default value with ??:


Adding and Updating Properties

Updating a value

Just assign a new value to the key.

Adding a new property

If the key doesn't exist yet, assigning a value creates it.

Wait, we used const, but the object changed? 🤔

Yes! Just like with arrays, const stops you from replacing the whole object. But you can change what's inside it.


Deleting Properties

Use the delete keyword to remove a property.


Checking if a Property Exists

Using the in operator

Using Object.hasOwn()

⚠️ Why not just check the value?

A value like 0, "", or false is falsy, so checking the value alone can mislead you. Use in or Object.hasOwn() to check whether the key exists.


Getting All Keys and Values

JavaScript gives us three helpful methods to look inside an object.

MethodReturns
Object.keys(obj)An array of all the keys
Object.values(obj)An array of all the values
Object.entries(obj)An array of key, value pairs

Looping through an object


Arrays of Objects

In real apps, you'll often have a list of objects, like a list of products, students, or orders. This combines arrays and objects together! 🤝


Common Mistakes to Avoid

MistakeProblemFix
Forgetting commas between properties❌ SyntaxErrorAdd , after each property
Using = instead of : inside { }❌ SyntaxErrorWrite name: "Priya", not name = "Priya"
Using obj.key when the key is in a variableGives undefinedUse obj[key]
Using dot notation with spaces (obj.first name)❌ SyntaxErrorUse obj["first name"]
Going deep into a missing object❌ TypeErrorUse optional chaining ?.
Checking existence with the value0 or "" look missingUse in or Object.hasOwn()
// ❌ Wrong
const user = { name = "Priya" age: 21 };

// ✅ Correct
const user = { name: "Priya", age: 21 };

Quick Summary Table

TaskCode
Create an objectconst obj = { name: "Priya", age: 21 };
Create an empty objectconst obj = {};
Read a valueobj.name or obj["name"]
Read with a variable keyobj[key]
Read a nested value safelyobj.address?.city
Add or updateobj.city = "Pune";
Deletedelete obj.age;
Check if a key exists"name" in obj
Get all keysObject.keys(obj)
Get all valuesObject.values(obj)
Count propertiesObject.keys(obj).length

Key Takeaways

  • An object stores related information as key: value pairs inside curly braces { }, like details on an ID card.
  • Use arrays for a list of similar items, and objects for the details of one thing.
  • Create objects with { } (the object literal). Use shorthand { name, age } when variable names match the keys.
  • Read values with dot notation (obj.key). Use bracket notation (obj["key"]) for keys with spaces, or when the key is in a variable.
  • You can add, update, and delete properties at any time, and use ?. to safely read nested values that might not exist.