Arrays

Easy

Arrays are ordered lists of values. They can hold any type and grow dynamically. JavaScript arrays come with powerful built-in methods like push, pop, map, filter, and reduce.

Interactive Visualization

Code
1let a = 5
2let b = a
3b = 10
4console.log(a, b)
5
6let arr1 = [1, 2, 3]
7let arr2 = arr1
8arr2.push(4)
9console.log(arr1)
Stack
(empty)
Heap
(empty)
Console Output
No output yet
Step 1/9Script starts. Stack and heap are empty.
Key Insight:Primitives are copied by VALUE (independent). Arrays are copied by REFERENCE (shared)!

Key Points

  • Arrays are zero-indexed (first element is at index 0)
  • Arrays can hold mixed types
  • length property gives the count of elements
  • Mutating methods: push, pop, shift, unshift, splice
  • Non-mutating methods: map, filter, slice, concat

Code Examples

Creating Arrays

// Array literal (preferred)
const fruits = ["apple", "banana", "cherry"];

// Array constructor (rare)
const numbers = new Array(1, 2, 3);

// Empty array
const empty = [];

// Mixed types (valid but unusual)
const mixed = [1, "hello", true, null];

Use array literals [] for creating arrays

Accessing Elements

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

fruits[0]          // "apple" (first)
fruits[2]          // "cherry" (third)
fruits[10]         // undefined (no error!)
fruits.length      // 3
fruits[fruits.length - 1]  // "cherry" (last)

// Modifying
fruits[1] = "orange";
// ["apple", "orange", "cherry"]

Access by index, use .length for size

Adding/Removing Elements

const arr = [1, 2, 3];

// Add to end
arr.push(4);       // [1, 2, 3, 4]

// Remove from end
arr.pop();         // [1, 2, 3]

// Add to beginning
arr.unshift(0);    // [0, 1, 2, 3]

// Remove from beginning
arr.shift();       // [1, 2, 3]

// All these MUTATE the original array!

push/pop for end, shift/unshift for beginning

map, filter, reduce

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

// map: transform each element
nums.map(n => n * 2);    // [2, 4, 6, 8, 10]

// filter: keep elements that pass test
nums.filter(n => n > 2); // [3, 4, 5]

// reduce: combine into single value
nums.reduce((sum, n) => sum + n, 0);  // 15

// These return NEW arrays (don't mutate)

map transforms, filter selects, reduce combines

Common Mistakes

  • Forgetting arrays are zero-indexed
  • Confusing methods that mutate vs return new arrays
  • Using delete on arrays (creates holes, use splice)

Interview Tips

  • Know which methods mutate vs return new arrays
  • Be comfortable with map, filter, reduce
  • Explain time complexity: push/pop O(1), shift/unshift O(n)

Related Concepts