Beginner · Arrays and objects · topic 16 of 61 · 25 min
Arrays: lists of values
Explanation
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.
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
| Method | What it does | Returns |
|---|---|---|
| push(x) | Adds x at the end | The new length |
| pop() | Removes the last item | The removed item |
| unshift(x) | Adds x at the start | The new length |
| shift() | Removes the first item | The removed item |
| splice(i, n, ...items) | Removes n items at index i, optionally inserting new ones | An array of removed items |
| slice(a, b) | Copies items from index a up to (not including) b | A NEW array |
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).
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]Searching
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).
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
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.
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)
Write lastItem(arr) that returns the last element of an array, or undefined for an empty array.
Write removeAt(arr, index) that returns a NEW array without the element at index. The original must not change.
Write topThree(scores) that returns the three highest scores, highest first, WITHOUT changing the original array.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Array methods: map, filter, reduce and friendsArrays and objects · same module
- Objects: keys and valuesArrays and objects · same module
- Destructuring, spread and restArrays and objects · same module
- Arrays and array methodsFrontend Web Development · JavaScript basics
- More array powerFrontend Web Development · JavaScript in depth
- Arrays and slicesGo Programming (backend and cloud) · Collections and structs
Questions people ask about this
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.
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".
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
- 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.
- Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.