Arrays and Objects

Site Admin · 11 Sep 2026 · 6 views

Arrays and Objects

Arrays and objects are the two most important data structures in JavaScript. Master them and you can model almost any real-world data.

Arrays

const fruits = ["apple", "banana", "cherry"];

fruits.push("date");          // Add to end
fruits.pop();                 // Remove from end
fruits.unshift("avocado");    // Add to front
fruits.shift();               // Remove from front

fruits[0];                    // "apple" (first element)
fruits.length;                // Number of elements
fruits.indexOf("banana");     // 1 (position or -1)
fruits.includes("cherry");    // true
fruits.slice(1, 3);           // ["banana", "cherry"]

Iterating Arrays

const numbers = [1, 2, 3, 4, 5];

// forEach - run code for each element
numbers.forEach(n => console.log(n));

// map - transform each element
const doubled = numbers.map(n => n * 2);  // [2, 4, 6, 8, 10]

// filter - keep matching elements
const even = numbers.filter(n => n % 2 === 0);  // [2, 4]

// find - first matching element
const firstBig = numbers.find(n => n > 3);  // 4

// reduce - accumulate a value
const sum = numbers.reduce((acc, n) => acc + n, 0);  // 15

// some / every - boolean checks
numbers.some(n => n > 4);   // true
numbers.every(n => n > 0);  // true

Objects

Objects store key-value pairs. They model real-world entities:

const user = {
    name: "Alice",
    age: 30,
    email: "alice@example.com",
    isAdmin: false,
    address: {
        city: "Berlin",
        zip: "10115"
    },
    greet() {
        return `Hi, I am ${this.name}`;
    }
};

user.name;                 // "Alice" (dot notation)
user["age"];               // 30 (bracket notation)
user.address.city;         // "Berlin" (nested access)
user.isAdmin = true;       // Update a property
user.phone = "555-1234";   // Add a new property
delete user.phone;         // Remove a property

Object Methods

const keys = Object.keys(user);        // ["name", "age", ...]
const values = Object.values(user);    // ["Alice", 30, ...]
const entries = Object.entries(user);  // [["name", "Alice"], ...]

Key Points

  • Arrays use zero-based indexing and offer push, pop, shift, unshift.
  • map, filter, and reduce handle most array transformations.
  • Objects store related data as key-value pairs.
  • Access properties with dot or bracket notation.
  • Object.keys, Object.values, and Object.entries inspect objects.
Share this post:

Comments (0)

Please login or register to comment.