Skip to main content

Arrays and Objects

Arrays and objects are the two data structures you will use in virtually every JavaScript project. Arrays store ordered lists of values; objects store key-value pairs.

Creating Arrays

const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = ["hello", 42, true, null];

Access elements by index (starting at 0):

console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits.length); // 3

Essential Array Methods

Adding and Removing Elements

const items = ["a", "b", "c"];

items.push("d");       // add to end    → ["a", "b", "c", "d"]
items.unshift("z");    // add to start  → ["z", "a", "b", "c", "d"]
items.pop();           // remove last   → ["z", "a", "b", "c"]
items.shift();         // remove first  → ["a", "b", "c"]
items.splice(1, 1);    // remove at index 1 → ["a", "c"]

Searching

const colors = ["red", "green", "blue", "green"];

console.log(colors.indexOf("green"));    // 1
console.log(colors.includes("blue"));    // true
console.log(colors.find((c) => c.startsWith("b"))); // "blue"
console.log(colors.findIndex((c) => c === "blue"));  // 2

Transforming Arrays

These methods return a new array without modifying the original.

map — Transform Every Element

const prices = [10, 20, 30];
const withTax = prices.map((price) => price * 1.1);

console.log(withTax); // [11, 22, 33]

filter — Keep Elements That Pass a Test

const scores = [85, 42, 93, 67, 78];
const passing = scores.filter((score) => score >= 70);

console.log(passing); // [85, 93, 78]

reduce — Accumulate a Single Value

const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((total, n) => total + n, 0);

console.log(sum); // 15

Chaining Methods

Array methods can be chained for powerful one-liners:

const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Phone", price: 699, inStock: false },
  { name: "Tablet", price: 449, inStock: true },
  { name: "Watch", price: 299, inStock: true },
];

const affordableInStock = products
  .filter((p) => p.inStock)
  .filter((p) => p.price < 500)
  .map((p) => p.name);

console.log(affordableInStock); // ["Tablet", "Watch"]

Sorting Arrays

The sort() method sorts in place and converts elements to strings by default.

const names = ["Charlie", "Alice", "Bob"];
names.sort();
console.log(names); // ["Alice", "Bob", "Charlie"]

// For numbers, you must provide a comparator
const nums = [10, 1, 21, 2];
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 10, 21]

Destructuring Arrays

Pull values out of arrays into named variables:

const rgb = [255, 128, 0];
const [red, green, blue] = rgb;

console.log(red);   // 255
console.log(green); // 128

// Skip values
const [first, , third] = [1, 2, 3];
console.log(third); // 3

// Rest pattern
const [head, ...tail] = [1, 2, 3, 4];
console.log(tail); // [2, 3, 4]

The Spread Operator

The spread operator ... expands an array into individual elements.

const a = [1, 2, 3];
const b = [4, 5, 6];
const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// Clone an array (shallow copy)
const original = [1, 2, 3];
const copy = [...original];

Creating Objects

const user = {
  name: "Sabaoon",
  age: 25,
  email: "hello@sabaoon.dev",
  isActive: true,
};

console.log(user.name);       // "Sabaoon"
console.log(user["email"]);   // "hello@sabaoon.dev"

Shorthand Properties

When the variable name matches the key name:

const name = "Alex";
const age = 28;

const person = { name, age }; // same as { name: name, age: age }

Destructuring Objects

const config = {
  host: "localhost",
  port: 3000,
  secure: false,
};

const { host, port, secure } = config;
console.log(host); // "localhost"
console.log(port); // 3000

// Rename variables
const { host: serverHost } = config;
console.log(serverHost); // "localhost"

// Default values
const { timeout = 5000 } = config;
console.log(timeout); // 5000

Iterating Over Objects

const scores = { math: 95, english: 87, science: 92 };

// Get keys
console.log(Object.keys(scores));   // ["math", "english", "science"]

// Get values
console.log(Object.values(scores)); // [95, 87, 92]

// Get entries
console.log(Object.entries(scores));
// [["math", 95], ["english", 87], ["science", 92]]

// Loop with for...of
for (const [subject, score] of Object.entries(scores)) {
  console.log(`${subject}: ${score}`);
}

Spreading and Merging Objects

const defaults = { theme: "light", language: "en", notifications: true };
const userPrefs = { theme: "dark", language: "en" };

const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme: "dark", language: "en", notifications: true }

Later spreads overwrite earlier ones for duplicate keys.

Optional Chaining

Safely access deeply nested properties without checking each level:

const user = {
  profile: {
    address: {
      city: "New York",
    },
  },
};

console.log(user.profile?.address?.city);    // "New York"
console.log(user.profile?.phone?.number);    // undefined (no error)
console.log(user.settings?.theme);           // undefined (no error)

Practical Exercise

Build a student grade tracker:

const students = [
  { name: "Alice", grades: [90, 85, 92] },
  { name: "Bob", grades: [78, 82, 75] },
  { name: "Charlie", grades: [95, 98, 100] },
  { name: "Diana", grades: [60, 55, 70] },
];

const report = students
  .map((student) => {
    const avg =
      student.grades.reduce((sum, g) => sum + g, 0) / student.grades.length;
    return { ...student, average: Math.round(avg) };
  })
  .sort((a, b) => b.average - a.average)
  .map(({ name, average }) => `${name}: ${average}%`);

console.log(report);
// ["Charlie: 98%", "Alice: 89%", "Bob: 78%", "Diana: 62%"]

Key Takeaways

  • Use map, filter, and reduce instead of manual loops for cleaner, more readable code.
  • Destructuring lets you extract values from arrays and objects into named variables.
  • The spread operator creates shallow copies and merges arrays or objects.
  • Optional chaining (?.) prevents errors when accessing nested properties that might not exist.
  • Chain array methods together for expressive data transformations.