Understanding Objects in JavaScript
What Are Objects?
You want to store information about a person:
Name: "Alice"
Age: 25
City: "Mumbai"
You could use separate variables:
let name = "Alice";
let age = 25;
let city = "Mumbai";
But that's messy. They're related but scattered.
Solution: Objects
const person = {
name: "Alice",
age: 25,
city: "Mumbai"
};
All related data in one place.
Objects store data as key-value pairs.
Why Objects Matter
Arrays store ordered lists:
const colors = ["red", "blue", "green"];
// Access by index: colors[0] = "red"
Objects store labeled data:
const car = {
brand: "Toyota",
model: "Camry",
year: 2020
};
// Access by key: car.brand = "Toyota"
Use arrays when: Order matters (list of items)
Use objects when: Labels matter (properties of a thing)
Creating Objects
Method 1: Object literal (most common)
const student = {
name: "Bob",
age: 20,
course: "Computer Science"
};
Method 2: Empty object, then add properties
const book = {};
book.title = "1984";
book.author = "Orwell";
book.pages = 328;
Method 3: Using new Object() (rarely used)
const user = new Object();
user.username = "alice123";
user.email = "alice@example.com";
Stick with object literals - cleanest syntax.
Object Structure
const objectName = {
key1: value1,
key2: value2,
key3: value3
};
Key (property name): Label for the data Value: The actual data
Example:
const laptop = {
brand: "HP", // key: brand, value: "HP"
price: 45000, // key: price, value: 45000
inStock: true, // key: inStock, value: true
color: "silver" // key: color, value: "silver"
};
Values can be any data type: string, number, boolean, array, even another object.
Accessing Object Properties
Two ways to access values:
1. Dot notation (most common)
const person = {
name: "Alice",
age: 25
};
console.log(person.name); // "Alice"
console.log(person.age); // 25
2. Bracket notation
console.log(person["name"]); // "Alice"
console.log(person["age"]); // 25
When to use bracket notation:
a) Property name has spaces or special characters
const user = {
"first name": "Alice",
"user-id": 123
};
// console.log(user.first name); // Error!
console.log(user["first name"]); // "Alice" ✓
console.log(user["user-id"]); // 123 ✓
b) Property name is in a variable
const person = {
name: "Alice",
age: 25
};
const key = "name";
console.log(person[key]); // "Alice"
const key2 = "age";
console.log(person[key2]); // 25
Dot notation: Use 95% of the time Bracket notation: Use when necessary
Updating Object Properties
Change existing values:
const student = {
name: "Bob",
grade: "B"
};
console.log(student.grade); // "B"
// Update
student.grade = "A";
console.log(student.grade); // "A"
Both notations work:
student.grade = "A+"; // Dot notation
student["grade"] = "A+"; // Bracket notation
Adding New Properties
Add properties that didn't exist:
const car = {
brand: "Toyota"
};
// Add new property
car.model = "Camry";
car.year = 2020;
console.log(car);
// { brand: "Toyota", model: "Camry", year: 2020 }
Dynamic adding:
const product = {};
product.name = "Laptop";
product.price = 50000;
product.inStock = true;
console.log(product);
// { name: "Laptop", price: 50000, inStock: true }
Deleting Properties
Remove properties using delete:
const user = {
username: "alice123",
password: "secret",
email: "alice@example.com"
};
delete user.password;
console.log(user);
// { username: "alice123", email: "alice@example.com" }
Checking if property exists:
const car = {
brand: "Toyota"
};
console.log("brand" in car); // true
console.log("model" in car); // false
Looping Through Object Properties
for...in loop iterates over object keys:
const student = {
name: "Alice",
age: 20,
course: "CS"
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
Output:
name: Alice
age: 20
course: CS
Getting all keys:
const person = {
name: "Bob",
age: 25,
city: "Delhi"
};
const keys = Object.keys(person);
console.log(keys);
// ["name", "age", "city"]
Getting all values:
const values = Object.values(person);
console.log(values);
// ["Bob", 25, "Delhi"]
Getting key-value pairs:
const entries = Object.entries(person);
console.log(entries);
// [["name", "Bob"], ["age", 25], ["city", "Delhi"]]
Objects Can Contain Anything
Arrays as values:
const student = {
name: "Alice",
grades: [85, 90, 88],
subjects: ["Math", "Science", "English"]
};
console.log(student.grades[0]); // 85
console.log(student.subjects[1]); // "Science"
Objects as values (nested objects):
const person = {
name: "Alice",
address: {
street: "MG Road",
city: "Mumbai",
pincode: 400001
}
};
console.log(person.address.city); // "Mumbai"
console.log(person.address.pincode); // 400001
Functions as values (methods):
const calculator = {
add: function(a, b) {
return a + b;
},
multiply: function(a, b) {
return a * b;
}
};
console.log(calculator.add(5, 3)); // 8
console.log(calculator.multiply(4, 2)); // 8
Shorthand for methods:
const calculator = {
add(a, b) {
return a + b;
},
multiply(a, b) {
return a * b;
}
};
Arrays vs Objects
Array:
const fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
Ordered list
Access by index (0, 1, 2...)
Good for lists of similar items
Object:
const person = {
name: "Alice",
age: 25,
city: "Mumbai"
};
console.log(person.name); // "Alice"
console.log(person.age); // 25
Key-value pairs
Access by property name
Good for describing a single entity
When to use which:
Use Array:
const students = ["Alice", "Bob", "Charlie"];
const scores = [85, 90, 78];
Use Object:
const student = {
name: "Alice",
score: 85,
grade: "A"
};
Combine both:
const classroom = [
{ name: "Alice", score: 85 },
{ name: "Bob", score: 90 },
{ name: "Charlie", score: 78 }
];
console.log(classroom[0].name); // "Alice"
console.log(classroom[1].score); // 90
Practical Examples
Example 1: Product information
const product = {
id: 101,
name: "Wireless Mouse",
price: 599,
inStock: true,
category: "Electronics"
};
console.log("Product:", product.name);
console.log("Price: ₹" + product.price);
if (product.inStock) {
console.log("Available");
} else {
console.log("Out of stock");
}
Example 2: User profile
const user = {
username: "alice123",
email: "alice@example.com",
age: 25,
isPremium: false
};
// Update
user.age = 26;
user.isPremium = true;
// Add new property
user.lastLogin = "2026-03-15";
console.log(user);
Example 3: Shopping cart
const cart = {
items: [],
total: 0
};
// Add items
cart.items.push("Laptop");
cart.items.push("Mouse");
cart.total = 51000;
console.log("Items:", cart.items);
console.log("Total: ₹" + cart.total);
Practice Assignment
Task: Create a student object
// 1. Create object
const student = {
name: "Alice",
age: 20,
course: "Computer Science",
semester: 4
};
// 2. Print original
console.log("Student Info:");
console.log(student);
// 3. Update property
student.semester = 5;
console.log("\nUpdated semester:", student.semester);
// 4. Add new property
student.gpa = 8.5;
console.log("Added GPA:", student.gpa);
// 5. Loop through all properties
console.log("\nAll properties:");
for (let key in student) {
console.log(key + ": " + student[key]);
}
// 6. Get all keys
const keys = Object.keys(student);
console.log("\nKeys:", keys);
// 7. Get all values
const values = Object.values(student);
console.log("Values:", values);
Expected output:
Student Info:
{ name: 'Alice', age: 20, course: 'Computer Science', semester: 4 }
Updated semester: 5
Added GPA: 8.5
All properties:
name: Alice
age: 20
course: Computer Science
semester: 5
gpa: 8.5
Keys: [ 'name', 'age', 'course', 'semester', 'gpa' ]
Values: [ 'Alice', 20, 'Computer Science', 5, 8.5 ]
Common Mistakes
❌ Accessing non-existent property
const car = { brand: "Toyota" };
console.log(car.model); // undefined (no error, but not ideal)
✅ Check if property exists
if ("model" in car) {
console.log(car.model);
} else {
console.log("Model not specified");
}
❌ Using dot notation with spaces
const user = {
"first name": "Alice"
};
// console.log(user.first name); // Syntax error!
✅ Use bracket notation
console.log(user["first name"]); // "Alice"
❌ Modifying const object reference
const person = { name: "Alice" };
person = { name: "Bob" }; // Error! Can't reassign const
✅ Modify properties instead
const person = { name: "Alice" };
person.name = "Bob"; // ✓ Works
person.age = 25; // ✓ Works
Quick Reference
Create object:
const obj = {
key1: value1,
key2: value2
};
Access:
obj.key1 // Dot notation
obj["key1"] // Bracket notation
Update:
obj.key1 = newValue;
Add:
obj.newKey = value;
Delete:
delete obj.key1;
Loop:
for (let key in obj) {
console.log(key, obj[key]);
}
Methods:
Object.keys(obj) // Array of keys
Object.values(obj) // Array of values
Object.entries(obj) // Array of [key, value] pairs
You Now Understand Objects
What objects are (key-value pairs)
Creating objects
Accessing properties (dot and bracket notation)
Updating and adding properties
Deleting properties
Looping through objects
Arrays vs objects
When to Use Objects
Use objects when you need to:
Store related data together
Access data by meaningful names (not indexes)
Represent a real-world entity (person, product, user)
Organize configuration settings
Practice Ideas
Create objects for:
Book (title, author, pages, year)
Movie (title, director, rating, year)
Restaurant (name, cuisine, rating, location)
Phone (brand, model, price, features array)
Objects are fundamental to JavaScript.
Master them, and you'll write cleaner, more organized code.
Building JavaScript skills? Follow for more programming fundamentals.