Understanding Objects in JavaScript
What Are Objects and Why Are They Needed?
Imagine a real person.
A person has: name, age and city
If we store these separately:
let name = "Rahul";
let age = 22;
let city = "Bangalore";
These variables are not connected.
But in real life, these details belong to one person.
So we group them together using an object.
What is Object?
Object = Key - Value Pair Structure
An object stores data in key - value pairs.
Think of it like:
Key → Value
name → Rahul
age → 22
city → Bangalore
In JavaScript:
let person = {
name: "Rahul",
age: 22,
city: "Bangalore"
};
Here:
person→ object namename,age,city→ keys"Rahul",22,"Bangalore"→ values
How to create an object?
let car = {
brand: "Toyota",
model: "Innova",
year: 2023
};
This is the simplest and most used way.
Accessing Object Properties
There are two ways to access values.
Dot Notation
Bracket Notation
Dot Notation
console.log(person.name); // Rahul
console.log(person.age); // 22
Bracket Notation
console.log(person["city"]); // Bangalore
Bracket notation is useful when:
Property name is dynamic
Property name has spaces
Example:
let key = "name";
console.log(person[key]); // Rahul
Updating Object Properties
You can change values of any key in the objects easily.
person.age = 25;
console.log(person.age); // 25
Objects are mutable (values can change).
Adding and Deleting Properties
Adding New Property
person.country = "India";
console.log(person);
Now object becomes:
{
name: "Rahul",
age: 25,
city: "Bangalore",
country: "India"
}
Deleting Property
delete person.city;
console.log(person);
Now city is removed.
Looping Through Object Keys
To print all properties, use for...in loop.
for (let key in person) {
console.log(key + " : " + person[key]);
}
Output:
name : Rahul
age : 25
country : India
How it works:
keystores property nameperson[key]gives the value
Difference Between Array and Object
| Array | Object |
|---|---|
| Stores ordered list | Stores key-value pairs |
| Uses index (0,1,2...) | Uses named keys |
Example: ["Rahul", 22] |
Example: {name: "Rahul", age: 22} |
Assignment
Create an object representing a student
Add properties like name, age, course
Update one property
Print all keys and values using a loop
// Create an object representing a student with name, age and course
let student = {
name: "Visshnnu Tejaa",
age: 27,
course: "Web dev Cohort"
}
// Update age property
student.age = 28
// Print all keys and values using a loop
for (let key in student){
console.log(key, student[key])
}
Output:
"name", "Visshnnu Tejaa"
"age", 28
"course", "Web dev Cohort"