Arrays: ordered lists you can trust
Indexes, length, push and pop, slice vs splice, spread and destructuring.
Lesson 7 of 23 in JavaScript10 min1 exercise
An array holds values in order. Indexes start at 0, and length is one more than the last index. Arrays can hold anything, including other arrays.
const fruits = ["apple", "pear", "plum"];
fruits[0]; // "apple"
fruits.length; // 3
fruits[3]; // undefined
fruits.push("fig"); // add to the end, returns new length
fruits.pop(); // remove from the end, returns the item
fruits.unshift("kiwi"); // add to the start
fruits.shift(); // remove from the start
fruits.includes("pear"); // true
fruits.indexOf("plum"); // 2Copying instead of changing
push, pop, shift, unshift, splice and sort mutate the array. slice, concat, map and filter return a new one. Mutating shared data causes bugs that are hard to find, so prefer the copying methods.
const numbers = [1, 2, 3, 4, 5];
numbers.slice(1, 3); // [2, 3] (end not included)
numbers.slice(-2); // [4, 5] (from the end)
numbers.slice(); // a copy
const copy = [...numbers]; // spread: shallow copy
const [first, second, ...rest] = numbers;
// first = 1, second = 2, rest = [3, 4, 5]
const merged = [...numbers, 6]; // [1, 2, 3, 4, 5, 6]Try it
Mutating vs copying
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
Take the last N items
Write lastN(items, n) that returns a new array with the last n items. If n is larger than the array, return the whole array. If n is 0 or less, return an empty array. The original array must not change.
lastN([1, 2, 3, 4], 2) → [3, 4].
exercise.js
console · run your code or check the answer