Spex3
    

JavaScript Objects 🏗️


    

    

JavaScript Objects 🏗️
Objects are key-value pairs used to store related data and functions.

1️⃣ Creating Objects
✅ 1. Using Object Literals {} (Most Common)

 
let person = {
name: "Alice",
age: 25,
isStudent: false
};
console.log(person);


✅ 2. Using new Object() (Less Common)

let car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
car.year = 2022;

console.log(car);


2️⃣ Accessing Object Properties
✅ 1. Dot Notation .

console.log(person.name); // Output: Alice
console.log(person.age); // Output: 25


✅ 2. Bracket Notation []

console.log(person["name"]); // Output: Alice
let key = "age";
console.log(person[key]); // Output: 25

📌 Use bracket notation when keys are dynamic or contain spaces.

3️⃣ Modifying and Adding Properties

person.age = 30; // Modify
person.city = "New York"; // Add new property

console.log(person);
// { name: "Alice", age: 30, isStudent: false, city: "New York" }


4️⃣ Object Methods (Functions Inside Objects)

let person = {
name: "Alice",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};

person.greet(); // Output: Hello, my name is Alice


📌 this refers to the current object (person).

5️⃣ The this Keyword
The this keyword refers to the object that is executing the function.

✅ 1. Inside an Object Method

let user = {
name: "Bob",
sayHi() {
console.log("Hi, I'm " + this.name);
}
};
user.sayHi(); // Output: Hi, I'm Bob


✅ 2. this in Global Scope

console.log(this); // Refers to `window` in browsers


✅ 3. this in Arrow Functions (No Own this)

let person = {
name: "Alice",
greet: () => {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, undefined


📌 Arrow functions do not bind this, so it refers to the global object (window).

6️⃣ Looping Through Objects
✅ 1. Using for...in

let car = {
brand: "Toyota",
model: "Corolla",
year: 2022
};

for (let key in car) {
console.log(key + ": " + car[key]);
}
// Output:
// brand: Toyota
// model: Corolla

// year: 2022


✅ 2. Using Object.keys(), Object.values(), Object.entries()

console.log(Object.keys(car)); // ["brand", "model", "year"]
console.log(Object.values(car)); // ["Toyota", "Corolla", 2022]
console.log(Object.entries(car)); // [["brand", "Toyota"], ["model", "Corolla"], ["year", 2022]]

7️⃣ Nested Objects
Objects can have other objects as values.


let student = {
name: "John",
scores: {
math: 90,
science: 85
}
};
console.log(student.scores.math); // Output: 90


8️⃣ Summary
✅ Objects store key-value pairs.
✅ Access properties using . or [].
✅ Methods are functions inside objects.
✅ this refers to the current object.
✅ Use for...in or Object.keys() to loop through objects.


    Date: 2025-03-29 00:00:00.000000