JavaScript Objects π¶
Mentor's Note: In the real world, an "Item" has many features. A phone isn't just a number; it has a color, a model, and actions it can do. Objects allow us to model these real items in code! π‘
π The Scenario: The Luxury Car ποΈ¶
Imagine you are looking at a sports car.
- The Properties: The car has a Brand (Ferrari), a Color (Red) π΄, and a Top Speed (300km/h). π¦
- The Methods: The car can Start π, Drive ποΈ, and Stop π.
- The Result: You group all these features under one name:
myCar. β
π Concept Explanation¶
1. What is an Object?¶
An object is a collection of related data and/or functionality. These usually consist of several variables and functions, which are called Properties and Methods when they are inside objects.
2. Creating an Object¶
We use curly braces {} to create an object literal.
3. Accessing Data¶
- Dot Notation:
person.name(The professional way). π±οΈ - Bracket Notation:
person["name"](The dynamic way).
π¨ Visual Logic: The Object Container¶
graph LR
subgraph Object: ["myCar ποΈ"]
P1["brand: 'Ferrari'"]
P2["color: 'Red'"]
M1["start: function()"]
end
π» Implementation: The Object Lab¶
// π Scenario: Building a User Profile
// π Action: Creating properties and a method
const user = {
name: "Vishnu Digital",
course: "Full Stack JS",
isLoggedIn: true,
// βοΈ A Method (Action)
greet: function() {
console.log(`Hello, welcome to ${this.course}! π`);
}
};
// Accessing properties
console.log(user.name);
// Calling a method
user.greet();
π§ Step-by-Step Logic (The this Keyword)¶
- When you call
user.greet(), JavaScript looks inside theuserobject. - The word
thispoints back to the object itself (theuser). - So,
this.coursebecomes"Full Stack JS". - End π
π Sample Dry Run¶
| Instruction | Computer Action | Result |
|---|---|---|
user.age = 20 |
Add new label 'age' | {name:..., age: 20} |
delete user.age |
Remove label 'age' | {name:...} ποΈ |
π Technical Analysis¶
- Reference Type: Objects are stored as a reference. If you copy an object (
const a = b), you aren't making a new one; both names point to the Same memory box. π§
π― Practice Lab π§ͺ¶
Task: The Book Shelf
Task: Create an object book with properties title, author, and isRead (boolean). Add a method summary() that prints: "[Title] was written by [Author]."
Hint: Use this.title and this.author. π‘
π‘ Interview Tip π¶
"Interviewers love asking: 'What is the difference between an Object and an Array?' Answer: Arrays are ordered lists accessed by numbers (0, 1, 2). Objects are unordered collections accessed by names (keys)!"
π‘ Pro Tip: "Object-oriented programming is like building with LEGOsβyou create parts once and use them to build anything!" - Anonymous