Skip to content

JavaScript Objects πŸš€ΒΆ

Prerequisites: JavaScript Variables, JavaScript Functions

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.

const person = {
  name: "Vishnu",
  age: 25
};

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)¢

  1. When you call user.greet(), JavaScript looks inside the user object.
  2. The word this points back to the object itself (the user).
  3. So, this.course becomes "Full Stack JS".
  4. 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


← Back: Functions | Next: Events β†’