Skip to content
Lesson 5 of 10 · JavaScript for Beginners

Arrays

Store ordered lists, add and remove items, copy with spread, and unpack with destructuring.

18 min

An array is an ordered list of values, written with square brackets. Indexes start at 0.

javascript4 lines
const fruits = ["apple", "pear", "plum"];
console.log(fruits[0]);        // apple
console.log(fruits.length);    // 3
console.log(fruits[fruits.length - 1]);   // plum

javascript5 lines
fruits.push("fig");        // add to the end
fruits.pop();              // remove from the end, returns it
fruits.unshift("kiwi");    // add to the start
fruits.shift();            // remove from the start
fruits[1] = "cherry";      // replace by index

const stops you reassigning the variable, but you can still change what is inside the array.

fruits.includes("pear") gives true or false; fruits.indexOf("pear") gives the position or -1. slice(start, end) copies a piece without changing the array (end excluded); splice changes it in place. join(", ") makes a string; "a b c".split(" ") makes an array.

javascript2 lines
const more = [...fruits, "grape"];   // a new array
const copy = [...fruits];

Assigning an array to another variable (const b = a) does not copy it: both names point at the same array.

javascript1 line
const [first, second] = fruits;

pulls items out by position, in one line.

Common misconception

“`const b = a` makes a separate copy of the array.”

With numbers and strings, `b = a` really does give you an independent value.

What is actually true

Arrays (and objects) are stored by reference: both names point to one array, so b.push(1) also changes a. Make a copy with [...a] or a.slice().

How to catch yourself

If changing one array unexpectedly changes another, check whether you copied or just pointed.

Reference

Array methods that change vs copy

push(x)

Changes the array?
yes
Returns
new length

pop()

Changes the array?
yes
Returns
removed item

splice(i, n)

Changes the array?
yes
Returns
array of removed items

slice(a, b)

Changes the array?
no
Returns
new array

concat, spread [...a]

Changes the array?
no
Returns
new array

includes(x)

Changes the array?
no
Returns
true or false

Mutating methods are fine, but know which ones they are.

Exercise5 checks
javascript

Write chunk(arr, size) that splits an array into pieces of length size (the last may be shorter) and returns the array of pieces.

chunk([1, 2, 3, 4, 5], 2) is [[1, 2], [3, 4], [5]].

Your code must satisfy

  • chunk([1, 2, 3, 4, 5], 2)→[[1,2],[3,4],[5]]uneven
  • chunk([1, 2, 3, 4], 2)→[[1,2],[3,4]]exact
  • chunk([1, 2], 5)→[[1,2]]size larger
  • chunk([], 3)→[]empty
  • chunk(["a", "b"], 1)→[["a"],["b"]]size one
starter code3 lines
function chunk(arr, size) {
  
}
Exercise4 checks
javascript

Write unique(arr) that returns a new array with duplicates removed, keeping the first time each value appears.

unique([3, 1, 3, 2, 1]) is [3, 1, 2].

Your code must satisfy

  • unique([3, 1, 3, 2, 1])→[3,1,2]numbers
  • unique(["a", "b", "a"])→["a","b"]words
  • unique([])→[]empty
  • unique([1, 2, 3])→[1,2,3]no repeats
starter code3 lines
function unique(arr) {
  
}
  • Arrays are ordered lists indexed from 0; length is the count.
  • push, pop, shift, unshift and splice change the array; slice and spread copy.
  • Arrays are shared by reference: const b = a is not a copy.
  • Destructuring (const [a, b] = arr) unpacks by position.
Check yourself

Array checks.

1Numeric answer

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

2Multiple choice

What is [1, 2, 3, 4].slice(1, 3)?

  • A[1, 2, 3]
  • B[2, 3]
  • C[2, 3, 4]
  • D[1, 2]
3Multiple choice

const a = [1]; const b = a; b.push(2); What is a?

  • A[1]
  • B[1, 2]
  • C[2]
  • Derror
4Multiple choice

What is ["a", "b", "c"].indexOf("z")?

  • A0
  • B-1
  • Cundefined
  • Dnull
5Fill the blanks

To make a real copy of a, write [...].

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.