Table of Contents
Understanding Objects
Objects are collections of key-value pairs that represent real-world entities. They're fundamental to JavaScript programming.
Creating Objects
// Object literal (most common)
let person = {
name: "Alice",
age: 30,
city: "New York",
isEmployed: true
};
// Empty object
let emptyObj = {};
// Object constructor
let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2022;
Accessing Object Properties
let student = {
firstName: "John",
lastName: "Doe",
age: 20,
grades: [85, 92, 78]
};
// Dot notation
console.log(student.firstName); // "John"
console.log(student.age); // 20
// Bracket notation
console.log(student["lastName"]); // "Doe"
console.log(student["grades"]); // [85, 92, 78]
// Dynamic property access
let property = "age";
console.log(student[property]); // 20
Modifying Objects
let book = {
title: "JavaScript Guide",
author: "John Smith",
pages: 300
};
// Add new property
book.publisher = "Tech Books";
book["isbn"] = "978-1234567890";
// Modify existing property
book.pages = 350;
// Delete property
delete book.isbn;
console.log(book);
Object Methods
let calculator = {
result: 0,
add: function(num) {
this.result += num;
return this; // Return this for method chaining
},
subtract: function(num) {
this.result -= num;
return this;
},
multiply: function(num) {
this.result *= num;
return this;
},
getResult: function() {
return this.result;
},
reset: function() {
this.result = 0;
return this;
}
};
// Method chaining
let result = calculator.add(10).multiply(2).subtract(5).getResult();
console.log(result); // 15
Object Methods with ES6 Syntax
let user = {
name: "Alice",
email: "alice@example.com",
// Method shorthand
greet() {
return `Hello, I'm ${this.name}`;
},
// Arrow functions (be careful with 'this')
getInfo: () => {
// Arrow functions don't have their own 'this'
return "User information";
},
// Method with parameters
updateEmail(newEmail) {
this.email = newEmail;
return `Email updated to ${this.email}`;
}
};
console.log(user.greet());
console.log(user.updateEmail("alice.new@example.com"));
Object Destructuring
let person = {
name: "Bob",
age: 25,
city: "Boston",
country: "USA"
};
// Basic destructuring
let { name, age } = person;
console.log(name); // "Bob"
console.log(age); // 25
// Destructuring with different variable names
let { name: fullName, city: location } = person;
console.log(fullName); // "Bob"
console.log(location); // "Boston"
// Destructuring with default values
let { name: userName, profession = "Unknown" } = person;
console.log(profession); // "Unknown"
Object.keys(), Object.values(), Object.entries()
let product = {
name: "Laptop",
price: 999.99,
category: "Electronics",
inStock: true
};
// Get all keys
let keys = Object.keys(product);
console.log(keys); // ["name", "price", "category", "inStock"]
// Get all values
let values = Object.values(product);
console.log(values); // ["Laptop", 999.99, "Electronics", true]
// Get key-value pairs
let entries = Object.entries(product);
console.log(entries); // [["name", "Laptop"], ["price", 999.99], ...]
// Iterate through object
for (let [key, value] of Object.entries(product)) {
console.log(`${key}: ${value}`);
}
Constructor Functions
// Constructor function (traditional way)
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
this.introduce = function() {
return `Hi, I'm ${this.name}, ${this.age} years old from ${this.city}`;
};
}
// Create instances
let person1 = new Person("Alice", 30, "New York");
let person2 = new Person("Bob", 25, "Boston");
console.log(person1.introduce());
console.log(person2.introduce());
ES6 Classes
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
speak() {
return `${this.name} makes a sound`;
}
getInfo() {
return `${this.name} is a ${this.species}`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name, "Dog"); // Call parent constructor
this.breed = breed;
}
speak() {
return `${this.name} barks!`;
}
fetch() {
return `${this.name} fetches the ball!`;
}
}
let myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.speak()); // "Buddy barks!"
console.log(myDog.getInfo()); // "Buddy is a Dog"
console.log(myDog.fetch()); // "Buddy fetches the ball!"
Practice Exercises
// Exercise 1: Library system
class Book {
constructor(title, author, isbn, pages) {
this.title = title;
this.author = author;
this.isbn = isbn;
this.pages = pages;
this.isAvailable = true;
}
checkout() {
if (this.isAvailable) {
this.isAvailable = false;
return `"${this.title}" has been checked out`;
}
return `"${this.title}" is not available`;
}
return() {
this.isAvailable = true;
return `"${this.title}" has been returned`;
}
getInfo() {
return `${this.title} by ${this.author} (${this.pages} pages)`;
}
}
let book1 = new Book("JavaScript Guide", "John Doe", "123456789", 400);
console.log(book1.getInfo());
console.log(book1.checkout());
console.log(book1.checkout()); // Try to checkout again
console.log(book1.return());
// Exercise 2: Shopping cart
let shoppingCart = {
items: [],
addItem(name, price, quantity = 1) {
let existingItem = this.items.find(item => item.name === name);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.items.push({ name, price, quantity });
}
return `Added ${quantity} ${name}(s) to cart`;
},
removeItem(name) {
this.items = this.items.filter(item => item.name !== name);
return `Removed ${name} from cart`;
},
getTotal() {
return this.items.reduce((total, item) => {
return total + (item.price * item.quantity);
}, 0);
},
getItemCount() {
return this.items.reduce((count, item) => count + item.quantity, 0);
},
displayCart() {
if (this.items.length === 0) {
return "Cart is empty";
}
let display = "Shopping Cart:\n";
this.items.forEach(item => {
display += `${item.name} - $${item.price} x ${item.quantity} = $${(item.price * item.quantity).toFixed(2)}\n`;
});
display += `Total: $${this.getTotal().toFixed(2)}`;
return display;
}
};
// Test the shopping cart
console.log(shoppingCart.addItem("Laptop", 999.99));
console.log(shoppingCart.addItem("Mouse", 29.99, 2));
console.log(shoppingCart.displayCart());