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
};
| Term | Meaning | Example |
|---|---|---|
| Key (property name) | The label | name |
| Value | The data stored for that label | "Priya" |
| Property | One key: value pair | name: "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. 🎯
| Point | Array [ ] | Object { } |
|---|---|---|
| Stores data as | An ordered list | Labelled key: value pairs |
| Access items by | Position (index): arr[0] | Name (key): obj.name |
| Best for | A list of similar things | Details of one thing |
| Example | A list of cities | One 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 thing | Object properties |
|---|---|
| 👤 A user profile | name, email, phone, isLoggedIn |
| 📱 A product on a shopping site | name, price, brand, inStock |
| 🍕 A food order | orderId, items, total, status |
| 🚆 A train ticket | pnr, trainName, seat, date |
| 🏏 A cricket player | name, team, runs, wickets |
| ⚙️ App settings | theme, 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
| Point | Dot obj.key | Bracket obj["key"] |
|---|---|---|
| Easy to read | ✅ Yes | Less clean |
Keys with spaces or - | ❌ No | ✅ Yes |
| Key stored in a variable | ❌ No | ✅ Yes |
| Use it | Most of the time | When 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.
| Method | Returns |
|---|---|
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
| Mistake | Problem | Fix |
|---|---|---|
| Forgetting commas between properties | ❌ SyntaxError | Add , after each property |
Using = instead of : inside { } | ❌ SyntaxError | Write name: "Priya", not name = "Priya" |
Using obj.key when the key is in a variable | Gives undefined | Use obj[key] |
Using dot notation with spaces (obj.first name) | ❌ SyntaxError | Use obj["first name"] |
| Going deep into a missing object | ❌ TypeError | Use optional chaining ?. |
| Checking existence with the value | 0 or "" look missing | Use in or Object.hasOwn() |
// ❌ Wrong
const user = { name = "Priya" age: 21 };
// ✅ Correct
const user = { name: "Priya", age: 21 };
Quick Summary Table
| Task | Code |
|---|---|
| Create an object | const obj = { name: "Priya", age: 21 }; |
| Create an empty object | const obj = {}; |
| Read a value | obj.name or obj["name"] |
| Read with a variable key | obj[key] |
| Read a nested value safely | obj.address?.city |
| Add or update | obj.city = "Pune"; |
| Delete | delete obj.age; |
| Check if a key exists | "name" in obj |
| Get all keys | Object.keys(obj) |
| Get all values | Object.values(obj) |
| Count properties | Object.keys(obj).length |
Key Takeaways
- An object stores related information as
key: valuepairs 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.