Lesson 40 of 296
Arrays: the basics
What you will learn
- What an array is
- Reading and changing items by index
- Adding and removing items
- Finding items
slicevssplice- Arrays inside arrays
- Why
constarrays can still change
On this page
What is an array?
An array is an ordered list of values. It is written with square brackets, and items are separated by commas.
const fruits = ["apple", "banana", "cherry"];
const scores = [72, 85, 90];
const mixed = ["Sam", 30, true, null];
const empty = [];An array can hold any types, but usually all items are the same kind of thing.
Index and length
Each item has an index (position), starting at 0.
| Index | 0 | 1 | 2 |
|---|---|---|---|
| Item | "apple" | "banana" | "cherry" |
fruits[0] "apple"
fruits[2] "cherry"
fruits[3] undefined (no item there)
fruits.length 3
fruits[fruits.length - 1] "cherry" (the last item)
fruits.at(-1) "cherry" (the last item, newer way)Changing an item
fruits[1] = "blueberry";
console.log(fruits); ["apple", "blueberry", "cherry"]Adding and removing at the ends
| Method | What it does | Returns |
|---|---|---|
push(x) | Adds to the end | The new length |
pop() | Removes from the end | The removed item |
unshift(x) | Adds to the start | The new length |
shift() | Removes from the start | The removed item |
const list = ["b", "c"];
list.push("d"); ["b", "c", "d"]
list.unshift("a"); ["a", "b", "c", "d"]
list.pop(); returns "d", list is ["a", "b", "c"]
list.shift(); returns "a", list is ["b", "c"]Performance note: push and pop are fast. shift and unshift are slow on large arrays, because every other item must move to a new index. This becomes important in Part 10 (queues).
Finding items
| Method | Example | Result |
|---|---|---|
includes(x) | fruits.includes("apple") | true |
indexOf(x) | fruits.indexOf("cherry") | 2, or -1 if not found |
find(fn) | scores.find((s) => s > 80) | 85, the first match |
findIndex(fn) | scores.findIndex((s) => s > 80) | 1 |
find and findIndex take a callback (Lesson 39). Part 5 covers them with map, filter and reduce.
Joining and copying
["a", "b", "c"].join("-") "a-b-c"
["a", "b"].concat(["c"]) ["a", "b", "c"]slice vs splice
These two names look alike but do very different things. A classic interview question.
slice(start, end) | splice(start, count, ...newItems) | |
|---|---|---|
| Changes the original array? | No | Yes |
| Returns | A new array with the selected part | An array of the removed items |
end included? | No | - |
| Use for | Copying part of an array | Removing or inserting items in place |
const letters = ["a", "b", "c", "d", "e"];
letters.slice(1, 3); ["b", "c"] letters unchanged
letters.splice(1, 2); returns ["b", "c"]
console.log(letters); ["a", "d", "e"] changed!
letters.splice(1, 0, "x"); inserts "x" at index 1 without removing anything
console.log(letters); ["a", "x", "d", "e"]Arrays inside arrays
const grid = [
[1, 2, 3],
[4, 5, 6]
];
grid[1][2]; 6 (row 1, then column 2)These are called 2D arrays or matrices. You will use them in Part 10.
const arrays can still change
const cart = ["milk"];
cart.push("bread"); allowed: ["milk", "bread"]
cart = []; Error: Assignment to constant variable.const stops the variable pointing to a different array. It does not stop changes inside the array. The full reason (values vs references) is in Part 5.
Copying an array
const copy = [...original];The ... is the spread operator (Part 5). It creates a new array with the same items. Writing const copy = original; does not copy. Both names point to the same array, so changing one changes the other.
Checking for an array
Array.isArray(fruits) true
typeof fruits "object"Common mistakes
- Starting the index at 1.
fruits[fruits.length]for the last item (it isundefined).- Mixing up
sliceandsplice. - Thinking
const copy = originalmakes a copy. - Using
indexOfand checkingif (index). Index0is falsy, so an item at the start looks "not found". Checkindex !== -1.
How to say it in an interview
"An array is an ordered, zero-indexed list. push and pop work at the end and are fast; shift and unshift work at the start and are slower because items are re-indexed. slice returns a new array and does not change the original, while splice changes the array in place. A const array can still be mutated because const only prevents reassignment of the variable, and assigning an array to another variable copies the reference, not the array."
Key words
| Word | Meaning |
|---|---|
| Array | An ordered list of values |
| Element / item | One value in an array |
| Index | The position of an item, starting at 0 |
| Mutate | Change something in place |
| slice | Copy part of an array without changing it |
| splice | Remove or insert items in the original array |
| 2D array | An array of arrays, like a grid |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.