Skip to content

Beginner · Arrays and objects · topic 16 of 61 · 25 min

Arrays: lists of values

Explanation

An array is an ordered list of values, numbered from 0. You can add and remove items at the end (push, pop) or the start (unshift, shift), cut out parts (slice) and change parts in place (splice). Some methods change the original array and some return a new one, and knowing which is which prevents many bugs.

Why arrays?

A program rarely works with one value. It works with lists: the items in a cart, the marks of a class, the trains between two cities. An array keeps many values in one variable, in order. Each value is an element, and its position is its index, starting at 0.

javascript
const cities = ['Delhi', 'Mumbai', 'Chennai'];
console.log(cities[0]);        // 'Delhi'
console.log(cities.length);    // 3
console.log(cities.at(-1));    // 'Chennai'
console.log(cities[5]);        // undefined (no error)
cities[1] = 'Kolkata';         // replace an element
console.log(cities);           // ['Delhi', 'Kolkata', 'Chennai']

Adding and removing

MethodWhat it doesReturns
push(x)Adds x at the endThe new length
pop()Removes the last itemThe removed item
unshift(x)Adds x at the startThe new length
shift()Removes the first itemThe removed item
splice(i, n, ...items)Removes n items at index i, optionally inserting new onesAn array of removed items
slice(a, b)Copies items from index a up to (not including) bA NEW array
javascript
const queue = ['A1', 'A2', 'A3'];
queue.push('A4');          // ['A1', 'A2', 'A3', 'A4']
const served = queue.shift(); // 'A1'
queue.splice(1, 1);        // removes 'A3' → ['A2', 'A4']
const firstTwo = ['a', 'b', 'c'].slice(0, 2); // ['a', 'b']

Mutating versus non-mutating

A mutating method changes the original array: push, pop, shift, unshift, splice, sort, reverse and fill. A non-mutating method leaves the original alone and returns a new array: slice, concat, map, filter, and the newer toSorted, toReversed and with (added in ES2023).

javascript
const marks = [72, 95, 64];
const sorted = marks.toSorted((a, b) => a - b);
console.log(sorted); // [64, 72, 95]
console.log(marks);  // [72, 95, 64] unchanged
const fixed = marks.with(2, 66);  // copy with index 2 replaced
console.log(fixed);  // [72, 95, 66]
Careful: sort() and reverse() change the original array AND return it, which tricks people into thinking they made a copy. const sorted = list.sort() means list is sorted too. Use toSorted() or [...list].sort() when you need to keep the original.

Searching

javascript
const pins = ['110001', '400001', '600001'];
console.log(pins.includes('400001')); // true
console.log(pins.indexOf('600001'));  // 2
console.log(pins.indexOf('999999'));  // -1 (not found)

Arrays are objects

typeof [] is "object", so use Array.isArray(value) to test for arrays. Arrays can hold mixed types, but in practice keep one kind of thing per array: all numbers, or all order objects. Arrays are also copied by reference, so two variables can share one array (topic 5 of this module).

Think of it like this: An array is like the numbered lockers at a railway cloak room. Each locker has a number starting from 0, holds one thing, and you can add lockers at the end. splice is like removing a locker from the middle: everyone after it moves one place down.
Tip: Need the last element? arr.at(-1) is clearer than arr[arr.length - 1].

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Arrays: lists of values · 1/6

Arrays

In this lesson you will store lists of values in arrays.

Prefer a video by a teacher? Find free videos on “javascript arrays push pop slice splice tutorial” on YouTube ↗

In real life: A token queue at a clinic

A clinic's reception app keeps waiting patients in an array. New tokens are pushed at the end, the doctor calls the next patient with shift, and an emergency case is inserted at the front with unshift.

javascript
const waiting = ['T1', 'T2', 'T3'];
waiting.push('T4');
waiting.unshift('EMERGENCY');
const next = waiting.shift();
console.log(next, waiting); // EMERGENCY ['T1', 'T2', 'T3', 'T4']

Practice (0/3 done)

Task 1 · Code · Javascript

Write lastItem(arr) that returns the last element of an array, or undefined for an empty array.

Task 2 · Code · Javascript

Write removeAt(arr, index) that returns a NEW array without the element at index. The original must not change.

Task 3 · Code · Javascript

Write topThree(scores) that returns the three highest scores, highest first, WITHOUT changing the original array.

Quick quiz

Question 1

1.const a = [10, 20, 30]; What is a.indexOf(40)?

Question 2

2.What does [1, 2, 3].push(4) return?

Question 3

3.Which method does NOT change the original array?

Question 4

4.const a = [3, 1, 2]; const b = a.sort(); What is a?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

const a = [10, 20, 30]; What is a.indexOf(40)?

Answer: -1

indexOf returns -1 when the value is not found.

What does [1, 2, 3].push(4) return?

Answer: 4

push returns the new length of the array.

Which method does NOT change the original array?

Answer: slice

slice returns a new array and leaves the original alone.

const a = [3, 1, 2]; const b = a.sort(); What is a?

Answer: [1, 2, 3]

sort sorts in place and returns the same array, so a is sorted too.

Which method returns a new array with only the items that pass a test?Related

Answer: filter

filter keeps the items for which the callback returns true.

From Arrays and array methods

Which method does NOT change the original array?Related

Answer: toSorted()

toSorted returns a new sorted array. sort, reverse and splice all change the array they are called on.

From More array power

Can you compare two slices with ==?Related

Answer: No, only a slice with nil

Slices are not comparable; use slices.Equal to compare contents.

From Arrays and slices

What does slices.Index(s, x) return when x is not in s?Related

Answer: -1

Like many Go search functions, it returns -1 for "not found".

From Slices in depth: length, capacity and sharing

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Arrays and objects” before its exam: Array methods: map, filter, reduce and friends, Objects: keys and values, Destructuring, spread and rest, References, copies and equality.
  2. Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.

← Previous: Higher-order functions and recursion