Menu

HTML & JS Topic

JavaScript Arrays & Objects

Arrays: The Power of Modern Methods

Traditional Array Loops vs Modern Methods:

javascript

// Old way: for loop
const numbers = [1, 2, 3, 4, 5];
let doubled = [];
for (let i = 0; i < numbers.length; i++) {
    doubled.push(numbers[i] * 2);
}

// New way: map
const doubledModern = numbers.map(num => num * 2);

1. map() - Transform each element

Creates a new array by applying a function to each element.

javascript

// Basic transformation
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(num => num * num);
// [1, 4, 9, 16, 25]

// Transform objects
const users = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 }
];
const names = users.map(user => user.name);
// ['Alice', 'Bob']

const userGreetings = users.map(user => 
    `Hello, ${user.name}! You are ${user.age} years old.`
);
// ['Hello, Alice! You are 25 years old.', ...]

// With index
const numberedItems = ['apple', 'banana', 'cherry'].map((item, index) => 
    `${index + 1}. ${item}`
);
// ['1. apple', '2. banana', '3. cherry']

// Practical example: Format prices
const prices = [19.99, 29.99, 14.95];
const formattedPrices = prices.map(price => 
    `$${price.toFixed(2)}`
);
// ['$19.99', '$29.99', '$14.95']

2. filter() - Select elements based on condition

Creates a new array with elements that pass a test.

javascript

// Basic filtering
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(num => num % 2 === 0);
// [2, 4, 6, 8, 10]

const odds = numbers.filter(num => num % 2 !== 0);
// [1, 3, 5, 7, 9]

// Filter objects
const products = [
    { name: 'Laptop', price: 999, inStock: true },
    { name: 'Mouse', price: 29, inStock: false },
    { name: 'Keyboard', price: 79, inStock: true }
];

const inStockProducts = products.filter(product => product.inStock);
// [{name: 'Laptop', ...}, {name: 'Keyboard', ...}]

const affordableProducts = products.filter(product => product.price < 100);
// [{name: 'Mouse', ...}, {name: 'Keyboard', ...}]

// Complex filtering
const tasks = [
    { title: 'Write report', completed: true, priority: 'high' },
    { title: 'Email client', completed: false, priority: 'high' },
    { title: 'Update website', completed: false, priority: 'medium' }
];

const urgentTasks = tasks.filter(task => 
    !task.completed && task.priority === 'high'
);
// [{title: 'Email client', ...}]

// Remove falsy values
const data = [0, 1, false, 2, '', 3, null, 4, undefined, 5];
const truthyValues = data.filter(Boolean);
// [1, 2, 3, 4, 5]

3. reduce() - Accumulate values

Reduces array to a single value by applying a function.

javascript

// Sum all numbers
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, current) => 
    accumulator + current, 0
);
// 15

// Product of numbers
const product = numbers.reduce((acc, curr) => acc * curr, 1);
// 120

// Find maximum
const max = numbers.reduce((acc, curr) => 
    curr > acc ? curr : acc, -Infinity
);
// 5

// Group objects by property
const people = [
    { name: 'Alice', age: 25, city: 'NYC' },
    { name: 'Bob', age: 30, city: 'LA' },
    { name: 'Charlie', age: 25, city: 'NYC' },
    { name: 'Diana', age: 30, city: 'LA' }
];

const groupedByCity = people.reduce((acc, person) => {
    if (!acc[person.city]) {
        acc[person.city] = [];
    }
    acc[person.city].push(person);
    return acc;
}, {});
// { NYC: [...], LA: [...] }

// Flatten arrays
const nestedArrays = [[1, 2], [3, 4], [5, 6]];
const flattened = nestedArrays.reduce((acc, curr) => 
    [...acc, ...curr], []
);
// [1, 2, 3, 4, 5, 6]

// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitCount = fruits.reduce((acc, fruit) => {
    acc[fruit] = (acc[fruit] || 0) + 1;
    return acc;
}, {});
// { apple: 3, banana: 2, orange: 1 }

4. Other Essential Array Methods

javascript

// find() - Find first matching element
const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2);
// { id: 2, name: 'Bob' }

// findIndex() - Find index of first matching element
const index = users.findIndex(u => u.name === 'Charlie');
// 2

// some() - Check if at least one element passes test
const hasAdult = users.some(u => u.age >= 18);
// true or false

// every() - Check if all elements pass test
const allAdults = users.every(u => u.age >= 18);
// true or false

// sort() - Sort array (mutates original)
const scores = [5, 3, 8, 1, 4];
scores.sort((a, b) => a - b);  // Ascending
// [1, 3, 4, 5, 8]

scores.sort((a, b) => b - a);  // Descending
// [8, 5, 4, 3, 1]

// For objects
const products = [
    { name: 'Laptop', price: 999 },
    { name: 'Mouse', price: 29 },
    { name: 'Keyboard', price: 79 }
];
products.sort((a, b) => a.price - b.price);  // Sort by price

// forEach() - Execute function for each element
products.forEach(product => {
    console.log(`${product.name}: $${product.price}`);
});

// includes() - Check if array contains value
const colors = ['red', 'green', 'blue'];
colors.includes('green');  // true
colors.includes('yellow'); // false

Chaining Array Methods:

javascript

const products = [
    { name: 'Laptop', price: 999, category: 'electronics', rating: 4.5 },
    { name: 'Mouse', price: 29, category: 'electronics', rating: 4.2 },
    { name: 'Shirt', price: 49, category: 'clothing', rating: 4.7 },
    { name: 'Book', price: 19, category: 'books', rating: 4.8 }
];

// Get names of electronics products under $100, sorted by rating
const result = products
    .filter(product => 
        product.category === 'electronics' && product.price < 100
    )
    .sort((a, b) => b.rating - a.rating)
    .map(product => product.name);
// ['Mouse']

// Calculate total price of highly-rated items
const total = products
    .filter(product => product.rating >= 4.5)
    .map(product => product.price)
    .reduce((sum, price) => sum + price, 0);
// 1067 (Laptop + Shirt + Book)

Objects: Properties & Methods

Object Basics:

javascript

// Object literal
const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    isStudent: false,
    
    // Method (function as property)
    getFullName: function() {
        return `${this.firstName} ${this.lastName}`;
    },
    
    // Shorthand method syntax (ES6)
    greet() {
        return `Hello, my name is ${this.firstName}`;
    },
    
    // Computed property names
    ['id_' + Date.now()]: 'unique-id'
};

// Access properties
console.log(person.firstName);      // 'John'
console.log(person['lastName']);    // 'Doe' (bracket notation)
console.log(person.getFullName());  // 'John Doe'

// Dynamic property access
const property = 'age';
console.log(person[property]);      // 30

Object Methods:

javascript

const user = {
    name: 'Alice',
    age: 25,
    email: 'alice@example.com',
    address: {
        street: '123 Main St',
        city: 'NYC'
    }
};

// Object.keys() - Get property names
const keys = Object.keys(user);
// ['name', 'age', 'email', 'address']

// Object.values() - Get property values
const values = Object.values(user);
// ['Alice', 25, 'alice@example.com', {street: '123 Main St', city: 'NYC'}]

// Object.entries() - Get key-value pairs
const entries = Object.entries(user);
// [['name', 'Alice'], ['age', 25], ...]

// Object.assign() - Merge objects
const defaults = { theme: 'light', language: 'en' };
const preferences = { theme: 'dark' };
const merged = Object.assign({}, defaults, preferences);
// { theme: 'dark', language: 'en' }

// Object.freeze() - Prevent modifications
const frozen = Object.freeze(user);
// frozen.name = 'Bob' // Error in strict mode

// Object.seal() - Prevent adding/removing properties
const sealed = Object.seal(user);
// sealed.newProp = 'value' // Won't add
// sealed.name = 'Bob' // This works

// hasOwnProperty() - Check if property exists (not inherited)
user.hasOwnProperty('name');  // true
user.hasOwnProperty('toString');  // false (inherited)

Modern Object Features:

javascript

// Property shorthand
const name = 'John';
const age = 30;
const person = { name, age };  // Same as { name: name, age: age }

// Method shorthand (ES6)
const calculator = {
    add(a, b) { return a + b; },
    multiply(a, b) { return a * b; }
};

// Computed property names
const prefix = 'user_';
const id = 123;
const obj = {
    [prefix + id]: 'John Doe',
    [`get${prefix}Info`]() {
        return `User: ${this[prefix + id]}`;
    }
};

// Object spread operator (ES2018)
const defaults = { theme: 'light', fontSize: 14 };
const userSettings = { theme: 'dark' };
const finalSettings = { ...defaults, ...userSettings };
// { theme: 'dark', fontSize: 14 }

// Object.fromEntries() - Convert array to object
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries);
// { name: 'John', age: 30 }

// Optional chaining (ES2020)
const user = {
    profile: {
        name: 'John',
        address: {
            city: 'NYC'
        }
    }
};
const city = user.profile?.address?.city;  // 'NYC'
const country = user.profile?.address?.country;  // undefined (no error)
const zip = user.profile?.address?.zip?.code;  // undefined

// Nullish coalescing (ES2020)
const settings = {
    theme: null,
    fontSize: 0
};
const theme = settings.theme ?? 'light';  // 'light' (null/undefined only)
const fontSize = settings.fontSize ?? 14; // 0 (0 is not null/undefined)

Destructuring

Array Destructuring:

javascript

// Basic destructuring
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
// first = 'red', second = 'green', third = 'blue'

// Skip elements
const [primary, , tertiary] = colors;
// primary = 'red', tertiary = 'blue'

// Default values
const scores = [85, 90];
const [math = 0, science = 0, history = 0] = scores;
// math = 85, science = 90, history = 0

// Rest pattern
const numbers = [1, 2, 3, 4, 5];
const [firstNum, secondNum, ...rest] = numbers;
// firstNum = 1, secondNum = 2, rest = [3, 4, 5]

// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];  // a = 2, b = 1

// Nested arrays
const matrix = [[1, 2], [3, 4]];
const [[a, b], [c, d]] = matrix;
// a = 1, b = 2, c = 3, d = 4

// Function parameters
function getCoordinates() {
    return [40.7128, -74.0060];
}
const [latitude, longitude] = getCoordinates();

// Practical example
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`);

Object Destructuring:

javascript

// Basic destructuring
const user = {
    name: 'John',
    age: 30,
    email: 'john@example.com'
};
const { name, age, email } = user;
// name = 'John', age = 30, email = 'john@example.com'

// Renaming variables
const { name: userName, age: userAge } = user;
// userName = 'John', userAge = 30

// Default values
const { name, age, isAdmin = false } = user;
// isAdmin = false (if not in object)

// Rest pattern
const { name, ...otherInfo } = user;
// name = 'John', otherInfo = { age: 30, email: 'john@example.com' }

// Nested objects
const company = {
    name: 'Tech Corp',
    address: {
        street: '123 Main St',
        city: 'NYC'
    }
};
const { 
    name, 
    address: { 
        street, 
        city 
    } 
} = company;
// name = 'Tech Corp', street = '123 Main St', city = 'NYC'

// Function parameters
function printUser({ name, age }) {
    console.log(`${name} is ${age} years old`);
}
printUser(user);

// With default parameters
function createUser({ name = 'Anonymous', age = 0 } = {}) {
    return { name, age };
}
createUser();  // { name: 'Anonymous', age: 0 }
createUser({ name: 'John' });  // { name: 'John', age: 0 }

// Practical example
const config = {
    apiUrl: 'https://api.example.com',
    timeout: 5000,
    retries: 3,
    headers: {
        'Content-Type': 'application/json'
    }
};

const { 
    apiUrl, 
    timeout, 
    retries,
    headers: { 'Content-Type': contentType }
} = config;

Spread Operator (...)

Array Spread:

javascript

// Copy array
const original = [1, 2, 3];
const copy = [...original];
// copy = [1, 2, 3], original unchanged

// Merge arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2];
// [1, 2, 3, 4, 5, 6]

// Insert elements
const numbers = [1, 2, 3];
const withZero = [0, ...numbers, 4];
// [0, 1, 2, 3, 4]

// Convert string to array
const str = 'hello';
const chars = [...str];
// ['h', 'e', 'l', 'l', 'o']

// Remove duplicates
const duplicates = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(duplicates)];
// [1, 2, 3]

// Function arguments
const numbers = [1, 2, 3, 4, 5];
const max = Math.max(...numbers);
// 5

// Clone and add
const cart = ['apple', 'banana'];
const newCart = [...cart, 'orange'];
// ['apple', 'banana', 'orange']

const updatedCart = ['kiwi', ...cart.slice(1)];
// ['kiwi', 'banana'] (replace first item)

Object Spread:

javascript

// Copy object
const original = { a: 1, b: 2 };
const copy = { ...original };
// { a: 1, b: 2 }

// Merge objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };
// { a: 1, b: 2, c: 3, d: 4 }

// Override properties
const defaults = { theme: 'light', fontSize: 14 };
const userPrefs = { theme: 'dark' };
const settings = { ...defaults, ...userPrefs };
// { theme: 'dark', fontSize: 14 }

// Add properties
const user = { name: 'John', age: 30 };
const withEmail = { ...user, email: 'john@example.com' };
// { name: 'John', age: 30, email: 'john@example.com' }

// Remove properties (with destructuring)
const user = { name: 'John', age: 30, password: 'secret' };
const { password, ...safeUser } = user;
// safeUser = { name: 'John', age: 30 }

// Update nested object (shallow copy)
const user = {
    name: 'John',
    preferences: {
        theme: 'light',
        notifications: true
    }
};
const updatedUser = {
    ...user,
    preferences: {
        ...user.preferences,
        theme: 'dark'
    }
};
// preferences.theme is now 'dark', notifications remains true

// Conditional properties
const isAdmin = true;
const user = {
    name: 'John',
    ...(isAdmin && { role: 'admin' })
};
// { name: 'John', role: 'admin' } if isAdmin is true

Complete Practical Examples

Example 1: E-commerce Cart System

javascript

// Sample data
const products = [
    { id: 1, name: 'Laptop', price: 999, category: 'electronics', rating: 4.5 },
    { id: 2, name: 'Mouse', price: 29, category: 'electronics', rating: 4.2 },
    { id: 3, name: 'T-Shirt', price: 25, category: 'clothing', rating: 4.7 },
    { id: 4, name: 'Book', price: 19, category: 'books', rating: 4.8 },
    { id: 5, name: 'Headphones', price: 199, category: 'electronics', rating: 4.4 }
];

const cart = [
    { productId: 1, quantity: 1 },
    { productId: 3, quantity: 2 },
    { productId: 5, quantity: 1 }
];

// 1. Get cart items with full product details
const cartWithDetails = cart.map(cartItem => {
    const product = products.find(p => p.id === cartItem.productId);
    return {
        ...product,
        quantity: cartItem.quantity,
        total: product.price * cartItem.quantity
    };
});

console.log('Cart items:', cartWithDetails);

// 2. Calculate cart total
const cartTotal = cartWithDetails.reduce((total, item) => 
    total + item.total, 0
);
console.log('Cart total: $' + cartTotal);

// 3. Filter electronics products on sale (price < $100)
const affordableElectronics = products
    .filter(product => 
        product.category === 'electronics' && product.price < 100
    )
    .map(product => ({
        ...product,
        salePrice: product.price * 0.8  // 20% off
    }));

console.log('Affordable electronics:', affordableElectronics);

// 4. Group products by category
const productsByCategory = products.reduce((acc, product) => {
    const { category } = product;
    if (!acc[category]) {
        acc[category] = [];
    }
    acc[category].push(product);
    return acc;
}, {});

console.log('Products by category:', productsByCategory);

// 5. Add item to cart (immutable update)
function addToCart(cart, productId, quantity = 1) {
    // Check if product already in cart
    const existingIndex = cart.findIndex(item => item.productId === productId);
    
    if (existingIndex >= 0) {
        // Update quantity
        return cart.map((item, index) => 
            index === existingIndex 
                ? { ...item, quantity: item.quantity + quantity }
                : item
        );
    } else {
        // Add new item
        return [...cart, { productId, quantity }];
    }
}

const newCart = addToCart(cart, 2, 2);  // Add 2 mice
console.log('Updated cart:', newCart);

Example 2: User Management System

javascript

// Sample users data
const users = [
    { id: 1, name: 'Alice', age: 25, role: 'admin', active: true },
    { id: 2, name: 'Bob', age: 30, role: 'user', active: true },
    { id: 3, name: 'Charlie', age: 22, role: 'user', active: false },
    { id: 4, name: 'Diana', age: 28, role: 'moderator', active: true }
];

// 1. Get active user names
const activeUserNames = users
    .filter(user => user.active)
    .map(user => user.name);

console.log('Active users:', activeUserNames);

// 2. Get average age by role
const averageAgeByRole = users.reduce((acc, user) => {
    const { role, age } = user;
    if (!acc[role]) {
        acc[role] = { totalAge: 0, count: 0 };
    }
    acc[role].totalAge += age;
    acc[role].count += 1;
    return acc;
}, {});

// Calculate averages
Object.keys(averageAgeByRole).forEach(role => {
    const { totalAge, count } = averageAgeByRole[role];
    averageAgeByRole[role] = totalAge / count;
});

console.log('Average age by role:', averageAgeByRole);

// 3. Transform user data
const transformedUsers = users.map(user => {
    const { id, name, age, role, active } = user;
    return {
        userId: id,
        fullName: name.toUpperCase(),
        ageGroup: age < 25 ? 'Young' : age < 35 ? 'Adult' : 'Senior',
        role: role.charAt(0).toUpperCase() + role.slice(1),
        status: active ? 'Active' : 'Inactive'
    };
});

console.log('Transformed users:', transformedUsers);

// 4. Update user (immutable)
function updateUser(users, userId, updates) {
    return users.map(user => 
        user.id === userId 
            ? { ...user, ...updates }
            : user
    );
}

const updatedUsers = updateUser(users, 3, { active: true, age: 23 });
console.log('Updated user list:', updatedUsers);

// 5. User search with multiple criteria
function searchUsers(users, criteria) {
    return users.filter(user => {
        return Object.entries(criteria).every(([key, value]) => {
            if (key === 'minAge') return user.age >= value;
            if (key === 'maxAge') return user.age <= value;
            return user[key] === value;
        });
    });
}

const searchResults = searchUsers(users, { 
    role: 'user', 
    active: true,
    minAge: 25,
    maxAge: 35
});

console.log('Search results:', searchResults);

Example 3: Data Processing Pipeline

javascript

// Sample data: sales transactions
const transactions = [
    { id: 1, customer: 'Alice', amount: 150, date: '2024-01-15', category: 'electronics' },
    { id: 2, customer: 'Bob', amount: 89, date: '2024-01-15', category: 'clothing' },
    { id: 3, customer: 'Alice', amount: 45, date: '2024-01-16', category: 'books' },
    { id: 4, customer: 'Charlie', amount: 250, date: '2024-01-16', category: 'electronics' },
    { id: 5, customer: 'Bob', amount: 120, date: '2024-01-17', category: 'electronics' }
];

// 1. Daily sales report
const dailySales = transactions.reduce((acc, transaction) => {
    const { date, amount } = transaction;
    if (!acc[date]) {
        acc[date] = { total: 0, count: 0, transactions: [] };
    }
    acc[date].total += amount;
    acc[date].count += 1;
    acc[date].transactions.push(transaction);
    return acc;
}, {});

console.log('Daily sales:', dailySales);

// 2. Top customers by total spent
const customerSpending = transactions.reduce((acc, transaction) => {
    const { customer, amount } = transaction;
    acc[customer] = (acc[customer] || 0) + amount;
    return acc;
}, {});

// Convert to array and sort
const topCustomers = Object.entries(customerSpending)
    .map(([name, total]) => ({ name, total }))
    .sort((a, b) => b.total - a.total);

console.log('Top customers:', topCustomers);

// 3. Category statistics
const categoryStats = transactions.reduce((acc, transaction) => {
    const { category, amount } = transaction;
    if (!acc[category]) {
        acc[category] = { total: 0, count: 0, average: 0 };
    }
    acc[category].total += amount;
    acc[category].count += 1;
    acc[category].average = acc[category].total / acc[category].count;
    return acc;
}, {});

console.log('Category statistics:', categoryStats);

// 4. Filter and transform for report
const electronicsReport = transactions
    .filter(t => t.category === 'electronics')
    .map(t => ({
        transactionId: t.id,
        customer: t.customer.toUpperCase(),
        amount: t.amount,
        formattedAmount: `$${t.amount.toFixed(2)}`,
        date: new Date(t.date).toLocaleDateString('en-US')
    }))
    .sort((a, b) => b.amount - a.amount);

console.log('Electronics report:', electronicsReport);

// 5. Complex transformation with spread and destructuring
const enrichedTransactions = transactions.map(transaction => {
    // Destructure with defaults
    const { 
        id, 
        customer, 
        amount, 
        date, 
        category = 'uncategorized' 
    } = transaction;
    
    // Calculate derived properties
    const tax = amount * 0.08;  // 8% tax
    const total = amount + tax;
    
    // Create enriched object with spread
    return {
        ...transaction,
        tax,
        total,
        // Add status based on amount
        status: amount > 100 ? 'High Value' : 'Standard',
        // Add quarter based on date
        quarter: getQuarterFromDate(date)
    };
});

function getQuarterFromDate(dateString) {
    const month = new Date(dateString).getMonth();
    return Math.floor(month / 3) + 1;
}

console.log('Enriched transactions:', enrichedTransactions);

Modern Patterns & Tips

1. Optional Chaining with Arrays/Objects

javascript

const data = {
    users: [
        { name: 'John', address: { city: 'NYC' } }
    ]
};

// Safe access
const city = data.users?.[0]?.address?.city;  // 'NYC'
const country = data.users?.[0]?.address?.country;  // undefined

// With default values
const userCount = data.users?.length ?? 0;
const firstName = data.users?.[0]?.name ?? 'Anonymous';

2. Dynamic Property Names

javascript

// Compute property names
const dynamicKey = 'status';
const user = {
    name: 'John',
    [dynamicKey]: 'active',
    [`is${dynamicKey.charAt(0).toUpperCase() + dynamicKey.slice(1)}`]: true
};
// { name: 'John', status: 'active', isStatus: true }

// From array
const keys = ['name', 'age', 'city'];
const values = ['John', 30, 'NYC'];
const person = Object.fromEntries(
    keys.map((key, index) => [key, values[index]])
);
// { name: 'John', age: 30, city: 'NYC' }

3. Immutable Updates

javascript

const state = {
    users: [
        { id: 1, name: 'Alice', active: true },
        { id: 2, name: 'Bob', active: false }
    ],
    settings: { theme: 'light', notifications: true }
};

// Update user (immutable)
const updatedState = {
    ...state,
    users: state.users.map(user => 
        user.id === 2 
            ? { ...user, active: true, name: 'Robert' }
            : user
    )
};

// Toggle setting
const toggledSettings = {
    ...state,
    settings: {
        ...state.settings,
        notifications: !state.settings.notifications
    }
};

// Remove user
const filteredState = {
    ...state,
    users: state.users.filter(user => user.id !== 1)
};

4. Performance Tips

javascript

// Cache array length in loops
const arr = [/* large array */];
for (let i = 0, len = arr.length; i < len; i++) {
    // process
}

// Use Set for uniqueness checks
const duplicates = [1, 2, 2, 3, 3, 3];
const unique = Array.from(new Set(duplicates));

// Use Map for key-value lookups
const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
];
const userMap = new Map(users.map(user => [user.id, user]));
const user = userMap.get(1);  // Fast O(1) lookup

Common Mistakes to Avoid

javascript

// Modifying array during iteration
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num, index) => {
    if (num % 2 === 0) {
        numbers.splice(index, 1);  // Changes indices during loop!
    }
});

// Filter instead
const evens = numbers.filter(num => num % 2 === 0);

// Using map when you don't need new array
numbers.map(num => console.log(num));  // Creates unnecessary array

// Use forEach
numbers.forEach(num => console.log(num));

// Mutating objects directly
const user = { name: 'John', age: 30 };
function updateUser(user) {
    user.age = 31;  // Mutates original!
    return user;
}

// Create new object
function updateUser(user) {
    return { ...user, age: 31 };
}

// Not handling empty arrays in reduce
const emptyArray = [];
const sum = emptyArray.reduce((a, b) => a + b);  // Error!
// Provide initial value
const sum = emptyArray.reduce((a, b) => a + b, 0);

Quick Reference

Array Methods:

javascript

.map(fn)      // Transform each element
.filter(fn)   // Select elements that pass test
.reduce(fn, init) // Accumulate to single value
.find(fn)     // Find first matching element
.some(fn)     // Test if any element passes
.every(fn)    // Test if all elements pass
.sort(fn)     // Sort array
.forEach(fn)  // Execute for each element

Object Methods:

javascript

Object.keys(obj)     // Get property names
Object.values(obj)   // Get property values  
Object.entries(obj)  // Get [key, value] pairs
Object.assign(target, ...sources) // Merge objects
Object.freeze(obj)   // Prevent modifications
Object.seal(obj)     // Prevent adding/removing properties

Destructuring:

javascript

// Array
const [a, b, ...rest] = array;

// Object  
const { prop, prop: alias, prop = defaultValue } = object;
const { nested: { prop } } = object;

Spread Operator:

javascript

// Copy/merge arrays
const newArray = [...array1, ...array2];

// Copy/merge objects
const newObj = { ...obj1, ...obj2 };

Master these concepts and you'll write cleaner, more efficient JavaScript code!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?