Skip to content

Arrays

Arrays are ordered collections of values. JavaScript arrays are dynamic (grow/shrink automatically) and can hold mixed types. Modern array methods (map, filter, reduce, etc.) enable functional programming patterns.

// Creating arrays
const nums = [1, 2, 3, 4, 5];
const mixed = [1, "two", true, null];
const empty = [];
const from = Array.from("hello"); // ['h','e','l','l','o']
// Accessing elements
console.log(nums[0]); // 1
console.log(nums.length); // 5
console.log(nums.at(-1)); // 5 (last element)
// Common methods
nums.push(6); // add to end
nums.pop(); // remove from end
nums.unshift(0); // add to start
nums.shift(); // remove from start
// Array methods (functional)
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
const sum = nums.reduce((acc, n) => acc + n, 0);
// Finding elements
const found = nums.find(n => n > 3); // 4
const index = nums.findIndex(n => n > 3); // 3
const has = nums.includes(3); // true
// Transforming
const joined = nums.join(", "); // "1, 2, 3, 4, 5"
const sliced = nums.slice(1, 3); // [2, 3]
const sorted = [...nums].sort((a, b) => b - a); // [5, 4, 3, 2, 1]

Modifying array while iterating with forEach:

const arr = [1, 2, 3, 4, 5];
// BAD - modifying during iteration causes unexpected behavior
arr.forEach((val, i) => {
if (val % 2 === 0) arr.splice(i, 1); // Don't do this!
});
// GOOD - create new array
const odds = arr.filter(val => val % 2 !== 0);

Fix: Use filter to create a new array instead of mutating during iteration.

  1. How do you remove the last element from an array?

    Answer`arr.pop()` - removes and returns the last element.
  2. What does [1, 2, 3].map(x => x * 2) return?

    Answer`[2, 4, 6]` - map transforms each element.
  3. How do you combine two arrays?

    Answer`const combined = [...arr1, ...arr2]` or `arr1.concat(arr2)`