Arrays: Create, Mutate & Access

Master the fundamental data structure of the web. Learn how to store ordered lists, access data, and distinguish between mutating and non-mutating methods.

JavaScript8 min readConcept 26 of 62

The Array Data Structure

An Array is an ordered list of values. Unlike Objects, which use string keys to identify data, Arrays use numbered indexes.

Arrays are created using square brackets [], and their indexes always start counting at zero (0).

Mutating Methods (Destructive)

JavaScript provides several built-in methods that permanently change (mutate) the original array.

push(val) adds to the end, while pop() removes from the end.

unshift(val) adds to the beginning, while shift() removes from the beginning.

splice(start, deleteCount, ...items) is the ultimate mutator, capable of adding, removing, or replacing items anywhere in the array.

Non-Mutating Methods (Safe)

Some methods deliberately avoid changing the original array. Instead, they calculate a result and return a brand **new array**.

The most common is slice(start, end). It extracts a section of an array and returns it as a new copy, leaving the original perfectly intact.

concat(arr) merges two arrays together, returning a new, combined array.

The Array Workshop

Experiment with mutating methods (splice) versus non-mutating methods (slice) to see exactly how they impact the original data.

The Array Workshop

let arr = ["A", "B", "C", "D"];
// Array initialized
Execute:
Original Array (arr)
A
idx: 0
B
idx: 1
C
idx: 2
D
idx: 3
New Copy Returned
iNotice how push() and splice() destructively alter the original array, but slice() safely leaves it alone and generates a brand new copy!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the difference between `splice()` and `slice()`?
  2. 2If an array has 5 items, what is the index of the last item?
  3. 3Which method adds a new item to the very beginning of an array?

Remember this

  • Arrays are ordered collections accessed via zero-based numeric indexes.
  • push(), pop(), shift(), unshift(), and splice() permanently mutate the array.
  • slice() and concat() are non-mutating; they return a brand new copy.
  • The .length property automatically updates as you add or remove items.
  • Because arrays are objects, assigning them to new variables only copies the reference pointer, not the data.

Done with this concept?

Mark it complete to track your progress. No login needed.