Module 12 : Objects and Object Manipulation.
📚 1. Introduction to JavaScript Objects
✅ What is an Object?
An object is a non-primitive data type that allows you to store multiple collections of data using key-value pairs.
javascript
code
const person = { name: "John", age: 30, job: "Developer" };
name, age, job → keys (or properties)
"John", 30, "Developer" → values
✅ Why Use Objects?
To group related data together
To represent entities (like a user, product, or car)
Foundation for object-oriented programming (OOP)
🔨 2. Creating Objects
✅ Object Literals
javascript
code
let car = { brand: "Toyota", model: "Camry", year: 2020 };
✅ Using new Object()
javascript
code
let car = new Object(); car.brand = "Toyota"; car.model = "Camry"; car.year = 2020;
✅ Using Constructor Functions
javascript
code
function Person(name, age) { this.name = name; this.age = age; } let p1 = new Person("Alice", 25);
✅ Using ES6 Classes
javascript
code
class Animal { constructor(type, name) { this.type = type; this.name = name; } } let dog = new Animal("Dog", "Max");
🛠️ 3. Accessing and Manipulating Properties
✅ Accessing Properties
javascript
code
console.log(person.name); // Dot notation console.log(person["age"]); // Bracket notation
Use bracket notation when property names are dynamic or not valid identifiers (like first-name).
✅ Adding/Modifying Properties
javascript
code
person.city = "New York"; // Adding person.age = 31; // Modifying
✅ Deleting Properties
javascript
code
delete person.job;
🔁 4. Looping Through Objects
✅ Using for...in
javascript
code
for (let key in person) { console.log(`${key}: ${person[key]}`); }
✅ Using Object.keys(), Object.values(), Object.entries()
javascript
code
Object.keys(person); // ["name", "age", "city"] Object.values(person); // ["John", 31, "New York"] Object.entries(person); // [["name", "John"], ["age", 31], ["city", "New York"]]
🧩 5. Nested Objects and Access
javascript
code
const user = { id: 101, name: "Emma", address: { city: "Paris", postal: 75001 } }; console.log(user.address.city); // Paris
📦 6. Object Methods (Functions inside Objects)
javascript code
const student = { name: "Liam", greet: function () { console.log(`Hello, my name is ${this.name}`); } }; student.greet(); // Hello, my name is Liam
this refers to the object that calls the method.
📌 7. Object
javascript
code
const product = { name: "Laptop", price: 1200, brand: "Dell" }; const { name, price } = product; console.log(name); // Laptop
🔍 8. Advanced Object Manipulation
✅ Spread Operator (...)
javascript
code
const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; console.log(obj2); // { a: 1, b: 2, c: 3 }
✅ Object.freeze() and Object.seal()
javascript
code
const frozen = Object.freeze({ x: 1 }); // frozen.x = 2; // Not allowed const sealed = Object.seal({ y: 2 }); sealed.y = 3; // Allowed delete sealed.y; // Not allowed
🧠 9. Exercises with Explanations
🔸 Exercise 1: Create a student object with name, age, and a method to return a greeting
javascript
code
const student = { name: "Sara", age: 22, greet: function() { return `Hi, I’m ${this.name} and I’m ${this.age} years old.`; } }; console.log(student.greet());
✅ Explanation: Demonstrates object creation, property access, and method definition.
🔸 Exercise 2: Write a function that receives an object and prints its keys and values.
javascript
code
function printObjectDetails(obj) { for (let key in obj) { console.log(`${key}: ${obj[key]}`); } } printObjectDetails({ a: 10, b: 20 });
🔸 Exercise 3: Merge two objects using spread operator
javascript
code
let a = { x: 1 }; let b = { y: 2 }; let merged = { ...a, ...b }; console.log(merged); // { x: 1, y: 2 }
🔬 10. Insights
Why use objects in real apps?
Backend APIs return JSON objects
Objects represent complex entities (user, transaction, etc.)
Used in state management (e.g., React useState)
Performance:
Accessing object properties is fast (O(1))
Deep cloning large nested objects is expensive — avoid unnecessary deep copies
Modern Patterns:
Use object destructuring to reduce code repetition
Use Object.fromEntries() and Object.entries() to convert between arrays and objects
🧑🏫 Tips
Start with analogies: E.g., a person object with name, age, etc.
Use diagrams: Draw how keys and values connect
Code live: through modifying objects in the console
Prompt questions:
What happens when you access a non-existing property?
How can you dynamically create property names?
🔧 Create an object book with title, author, and year. Add a method summary() that returns a string like:
"Title" by Author (Year)
Then:
Update the year
Add a new property publisher
Print all keys and values
✅ Summary
Concept
Method / Syntax
Create Object
{} or new Object()
Access Property
obj.key / obj["key"]
Modify Property
obj.key = value
Delete Property
delete obj.key
Loop Through Object
for...in, Object.keys()
Clone/Merge Object
...spread, Object.assign()
Protect Object
Object.freeze(), Object.seal()
📘 Further Reading
MDN Web Docs - Working with Objects
"You Don’t Know JS" Book Series – Kyle Simpson
No comments:
Post a Comment