1) What is an Object?
An object stores data in key : value pairs.
Syntax
let mobile = {
brand: "Vivo",
model: "V70",
price: 25000
};
Here,
-
brand→ key -
"Vivo"→ value
Accessing Object Values
console.log(mobile.brand);
console.log(mobile.model);
Output
Vivo
V70
Real-World Example
let student = {
name: "Kavitha",
age: 20,
department: "EEE"
};
console.log(student.name);
Output:
Kavitha
2) Creating Object Inside an Object
This is called a nested object.
It means one object is stored inside another object.
Example: Mobile Object
let mobile = {
name: "Vivo",
model: "V70",
camera: {
rear: "32MP",
front: "64MP"
}
};
Here camera itself is another object.
Access Nested Object
console.log(mobile.camera.rear);
console.log(mobile.camera.front);
Output
32MP
64MP
Real-World Understanding
Think like this:
A student has an address
Address itself has:
- city
- state
- pincode
So:
let student = {
name: "Kavitha",
address: {
city: "Tirunelveli",
state: "Tamil Nadu",
pincode: 627001
}
};
Access:
console.log(student.address.city);
Output:
Tirunelveli
3) Creating Function Inside an Object
- When a function is created inside an object, it is called a method.
- Methods represent actions.
Example
let mobile = {
name: "Vivo",
call: function() {
console.log("Calling...");
}
};
Calling the Function
mobile.call();
Output:
Calling...
Short Modern Syntax
This is the cleaner way:
let mobile = {
name: "Vivo",
call() {
console.log("Calling...");
}
};
- This is commonly used.
4) Object + Nested Object + Function Together
- This is the complete structure
let mobile = {
name: "Vivo",
model: "V70",
camera: {
rear: "32MP",
front: "64MP"
},
display: {
size: "6.8 inch",
type: "AMOLED"
},
calling() {
console.log("Calling Amma...");
},
browsing() {
console.log("Browsing...");
}
};
Access Everything
console.log(mobile.name);
console.log(mobile.camera.front);
console.log(mobile.display.size);
mobile.calling();
mobile.browsing();
Output
Vivo
64MP
6.8 inch
Calling Amma...
Browsing...
Why Do We Use This?
This is heavily used in:
- JavaScript projects
- React
- APIs
- JSON data
- backend responses
- real-world applications
Example:
user.profile.name
product.details.price
robot.sensor.temperature
Simple Memory Trick
Object = thing
Nested object = thing inside thing
Function inside object = action of that thing
Example:
- Car → object
- Engine → object inside object
- Start → function inside object
Top comments (0)