stackademic

The leading education platform for anyone with an interest in software development.

Arrays

Create, access, and mutate ordered lists of values

Overview

Arrays are ordered, zero-indexed collections. JavaScript arrays are dynamic—they can grow and hold mixed types. Modern code favors immutable patterns (spread, map, filter) over mutating methods when sharing data.

Syntax / Usage

const nums = [1, 2, 3]
const mixed = ['a', 42, true]

// Access
nums[0]        // 1
nums.at(-1)    // 3 (last item)

// Mutating (change in place)
nums.push(4)
nums.pop()
nums.unshift(0)
nums.splice(1, 1)

// Non-mutating copies
const copy = [...nums]
const extended = [...nums, 5]

// Destructuring
const [first, second, ...rest] = nums

Examples

Build a unique tag list:

const tags = ['js', 'web', 'js', 'api']
const unique = [...new Set(tags)]
// ['js', 'web', 'api']

Find and update an item immutably:

const users = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bob' }]
const updated = users.map((u) =>
  u.id === 2 ? { ...u, name: 'Robert' } : u
)

Common Mistakes

  • Assuming sort() copies the array—it mutates in place
  • Using == on array elements when === is intended
  • Sparse arrays with holes behave oddly in map and forEach
  • Confusing array-like objects (NodeList) with real arrays—use Array.from

See Also

array-methods objects destructuring spread-rest