Master JavaScript objects - the cornerstone of modern programming. Learn to create, manipulate, and work with objects, understand property access, methods, and object-oriented programming concepts.
Master JavaScript objects - the cornerstone of modern programming. Learn to create, manipulate, and work with objects, understand property access, methods, and object-oriented programming concepts.
Objects are collections of key-value pairs that represent real-world entities:
1// Object literal notation (most common)
2const person = {
3 name: "Alice",
4 age: 28,
5 city: "New York",
6 isStudent: false
7};
8
9// Constructor notation
10const car = new Object();
11car.make = "Toyota";
12car.model = "Camry";
13car.year = 2024;
14
15// Object.create() method
16const animal = Object.create(null);
17animal.type = "Dog";
18animal.breed = "Golden Retriever";Two ways to access object properties:
1const user = {
2 firstName: "John",
3 lastName: "Doe",
4 email: "[email protected]",
5 "phone number": "555-1234" // Property with spaces
6};
7
8// Dot notation (preferred when possible)
9console.log(user.firstName); // "John"
10console.log(user.email); // "[email protected]"
11
12// Bracket notation (required for special property names)
13console.log(user["lastName"]); // "Doe"
14console.log(user["phone number"]); // "555-1234"
15
16// Dynamic property access
17const property = "email";
18console.log(user[property]); // "[email protected]"Objects are mutable - you can change them after creation:
1const student = {
2 name: "Sarah",
3 grade: "A"
4};
5
6// Adding new properties
7student.age = 20;
8student["major"] = "Computer Science";
9
10// Modifying existing properties
11student.grade = "A+";
12student["name"] = "Sarah Johnson";
13
14console.log(student);
15// { name: "Sarah Johnson", grade: "A+", age: 20, major: "Computer Science" }
16
17// Deleting properties
18delete student.age;
19console.log(student); // age property is goneObjects can contain functions as properties (called methods):
1const calculator = {
2 result: 0,
3
4 add: function(number) {
5 this.result += number;
6 return this; // Return object for method chaining
7 },
8
9 subtract: function(number) {
10 this.result -= number;
11 return this;
12 },
13
14 multiply: function(number) {
15 this.result *= number;
16 return this;
17 },
18
19 // ES6 shorthand method syntax
20 divide(number) {
21 if (number !== 0) {
22 this.result /= number;
23 }
24 return this;
25 },
26
27 getResult() {
28 return this.result;
29 },
30
31 reset() {
32 this.result = 0;
33 return this;
34 }
35};
36
37// Method chaining
38calculator.add(10).multiply(2).subtract(5);
39console.log(calculator.getResult()); // 15this refers to the object that owns the method:
1const person = {
2 firstName: "Alice",
3 lastName: "Smith",
4
5 getFullName: function() {
6 return this.firstName + " " + this.lastName;
7 },
8
9 introduce: function() {
10 return `Hi, I'm ${this.getFullName()}`;
11 },
12
13 // Arrow functions don't have their own "this"
14 arrowMethod: () => {
15 // "this" here refers to global scope, not the object
16 return this.firstName; // Won't work as expected
17 }
18};
19
20console.log(person.introduce()); // "Hi, I'm Alice Smith"Create multiple objects with the same structure:
1function Person(firstName, lastName, age) {
2 this.firstName = firstName;
3 this.lastName = lastName;
4 this.age = age;
5
6 this.getFullName = function() {
7 return `${this.firstName} ${this.lastName}`;
8 };
9
10 this.introduce = function() {
11 return `Hello, I'm ${this.getFullName()} and I'm ${this.age} years old.`;
12 };
13}
14
15// Create instances
16const person1 = new Person("John", "Doe", 30);
17const person2 = new Person("Jane", "Smith", 25);
18
19console.log(person1.introduce());
20console.log(person2.getFullName());ES6 classes provide a cleaner syntax:
1class BankAccount {
2 constructor(accountHolder, initialBalance = 0) {
3 this.accountHolder = accountHolder;
4 this.balance = initialBalance;
5 this.transactions = [];
6 }
7
8 deposit(amount) {
9 if (amount > 0) {
10 this.balance += amount;
11 this.transactions.push({ type: "deposit", amount, date: new Date() });
12 }
13 }
14
15 withdraw(amount) {
16 if (amount > 0 && amount <= this.balance) {
17 this.balance -= amount;
18 this.transactions.push({ type: "withdrawal", amount, date: new Date() });
19 }
20 }
21
22 getBalance() {
23 return this.balance;
24 }
25
26 getStatement() {
27 return `Account: ${this.accountHolder}, Balance: $${this.balance}`;
28 }
29}
30
31const account = new BankAccount("Alice Johnson", 1000);
32account.deposit(250);
33account.withdraw(100);
34console.log(account.getStatement());JavaScript provides utilities to work with object properties:
1const product = {
2 name: "Laptop",
3 price: 999,
4 category: "Electronics",
5 inStock: true
6};
7
8// Object.keys() - get all property names
9const keys = Object.keys(product);
10console.log(keys); // ["name", "price", "category", "inStock"]
11
12// Object.values() - get all property values
13const values = Object.values(product);
14console.log(values); // ["Laptop", 999, "Electronics", true]
15
16// Object.entries() - get key-value pairs as arrays
17const entries = Object.entries(product);
18console.log(entries);
19// [["name", "Laptop"], ["price", 999], ["category", "Electronics"], ["inStock", true]]
20
21// Iterate through object properties
22Object.entries(product).forEach(([key, value]) => {
23 console.log(`${key}: ${value}`);
24});Different ways to copy and combine objects:
1const original = {
2 name: "John",
3 age: 30,
4 address: {
5 city: "New York",
6 state: "NY"
7 }
8};
9
10// Shallow copy methods
11const copy1 = Object.assign({}, original);
12const copy2 = { ...original }; // Spread operator (preferred)
13
14// Modify copy
15copy2.name = "Jane";
16copy2.address.city = "Boston"; // This affects original too (shallow copy)
17
18console.log(original.address.city); // "Boston" - nested objects are shared!
19
20// Deep copy (for nested objects)
21const deepCopy = JSON.parse(JSON.stringify(original));
22deepCopy.address.state = "CA";
23console.log(original.address.state); // Still "NY" - deep copy worked
24
25// Object merging
26const defaults = { theme: "light", language: "en" };
27const userSettings = { theme: "dark" };
28const finalSettings = { ...defaults, ...userSettings };
29console.log(finalSettings); // { theme: "dark", language: "en" }Advanced object manipulation:
1const obj = {};
2
3// Define property with descriptor
4Object.defineProperty(obj, "readOnlyProp", {
5 value: "Cannot change this",
6 writable: false,
7 enumerable: true,
8 configurable: false
9});
10
11// Object.freeze() - prevent all modifications
12const frozenObj = Object.freeze({ name: "Frozen" });
13// frozenObj.name = "New"; // Won't work
14// frozenObj.age = 25; // Won't work
15
16// Object.seal() - prevent adding/removing properties
17const sealedObj = Object.seal({ name: "Sealed" });
18sealedObj.name = "Modified"; // This works
19// sealedObj.age = 25; // This won't work
20
21// Check object state
22console.log(Object.isFrozen(frozenObj)); // true
23console.log(Object.isSealed(sealedObj)); // trueExtract properties into variables:
1const user = {
2 name: "Alice",
3 email: "[email protected]",
4 age: 28,
5 preferences: {
6 theme: "dark",
7 language: "en"
8 }
9};
10
11// Basic destructuring
12const { name, email } = user;
13console.log(name, email); // "Alice", "[email protected]"
14
15// Rename variables
16const { name: fullName, age: userAge } = user;
17console.log(fullName, userAge); // "Alice", 28
18
19// Default values
20const { phone = "Not provided" } = user;
21console.log(phone); // "Not provided"
22
23// Nested destructuring
24const { preferences: { theme, language } } = user;
25console.log(theme, language); // "dark", "en"
26
27// Function parameters destructuring
28function greetUser({ name, age }) {
29 return `Hello ${name}, you are ${age} years old`;
30}
31
32console.log(greetUser(user)); // "Hello Alice, you are 28 years old"Real-world data often involves complex nested structures:
1const company = {
2 name: "Tech Solutions Inc",
3 founded: 2010,
4 headquarters: {
5 address: {
6 street: "123 Main St",
7 city: "San Francisco",
8 state: "CA",
9 zipCode: "94105"
10 },
11 phone: "555-0123"
12 },
13 departments: {
14 engineering: {
15 employees: 25,
16 manager: {
17 name: "Alice Johnson",
18 email: "[email protected]"
19 }
20 },
21 sales: {
22 employees: 15,
23 manager: {
24 name: "Bob Smith",
25 email: "[email protected]"
26 }
27 }
28 }
29};
30
31// Accessing nested properties
32console.log(company.headquarters.address.city); // "San Francisco"
33console.log(company.departments.engineering.manager.name); // "Alice Johnson"
34
35// Safe nested access
36function getNestedProperty(obj, path, defaultValue = null) {
37 return path.split('.').reduce((current, prop) => {
38 return current && current[prop] !== undefined ? current[prop] : defaultValue;
39 }, obj);
40}
41
42console.log(getNestedProperty(company, "headquarters.address.city")); // "San Francisco"
43console.log(getNestedProperty(company, "departments.marketing.manager")); // nullCommon pattern for representing collections:
1const products = [
2 {
3 id: 1,
4 name: "Laptop",
5 price: 999.99,
6 category: "Electronics",
7 specs: {
8 ram: "16GB",
9 storage: "512GB SSD",
10 processor: "Intel i7"
11 },
12 reviews: [
13 { user: "Alice", rating: 5, comment: "Excellent performance!" },
14 { user: "Bob", rating: 4, comment: "Good value for money" }
15 ]
16 },
17 {
18 id: 2,
19 name: "Book",
20 price: 29.99,
21 category: "Education",
22 specs: {
23 pages: 350,
24 author: "Jane Doe",
25 publisher: "Tech Books"
26 },
27 reviews: [
28 { user: "Charlie", rating: 5, comment: "Very informative" }
29 ]
30 }
31];
32
33// Process array of objects
34const expensiveProducts = products.filter(product => product.price > 500);
35const averageRating = product => {
36 const total = product.reviews.reduce((sum, review) => sum + review.rating, 0);
37 return total / product.reviews.length;
38};
39
40console.log(`Laptop average rating: ${averageRating(products[0])}`);Building complex objects from simpler ones:
1// Factory functions for creating objects
2function createAddress(street, city, state, zipCode) {
3 return { street, city, state, zipCode };
4}
5
6function createPerson(name, email) {
7 return {
8 name,
9 email,
10 addresses: [],
11
12 addAddress(type, street, city, state, zipCode) {
13 this.addresses.push({
14 type,
15 ...createAddress(street, city, state, zipCode)
16 });
17 },
18
19 getAddress(type) {
20 return this.addresses.find(addr => addr.type === type);
21 },
22
23 getFullProfile() {
24 return {
25 personalInfo: {
26 name: this.name,
27 email: this.email
28 },
29 addresses: this.addresses
30 };
31 }
32 };
33}
34
35const person = createPerson("John Doe", "[email protected]");
36person.addAddress("home", "123 Oak St", "Portland", "OR", "97201");
37person.addAddress("work", "456 Pine Ave", "Portland", "OR", "97202");
38
39console.log(person.getFullProfile());Your progress is saved in this browser, on this device only.