JavaScript Fundamentals

Objects and Arrays

Understanding Objects and Arrays

Objects and Arrays are fundamental data structures in JavaScript. Arrays are ordered collections of values, while objects are collections of key-value pairs. Understanding how to work with these structures is crucial for effective JavaScript programming.

Working with Arrays

// Array Creation and Methods
let fruits = ['apple', 'banana', 'orange'];
let numbers = [1, 2, 3, 4, 5];

// Array Methods
fruits.push('grape');           // Add to end
fruits.pop();                   // Remove from end
fruits.unshift('mango');        // Add to start
fruits.shift();                 // Remove from start
fruits.slice(1, 3);            // Get subset
fruits.splice(1, 1, 'kiwi');   // Replace elements

Working with Objects

// Object Creation and Properties
let person = {
  name: 'John',
  age: 25,
  hobbies: ['reading', 'music'],
  address: {
    street: '123 Main St',
    city: 'Boston'
  }
};

// Accessing and Modifying
person.name = 'Jane';           // Dot notation
person['age'] = 26;            // Bracket notation
delete person.hobbies;         // Remove property

Modern Features

// Modern Array and Object Features
// Array Destructuring
let [first, second, ...rest] = numbers;

// Object Destructuring
let { name, age } = person;

// Spread Operator
let newFruits = [...fruits, 'pear'];
let updatedPerson = { ...person, age: 27 };

// Array Methods
let doubled = numbers.map(n => n * 2);
let evens = numbers.filter(n => n % 2 === 0);
let sum = numbers.reduce((a, b) => a + b, 0);