JavaScript Arrays
An array is an ordered list of values stored under a single name. Instead of item1, item2, item3… you keep all the items in one variable and access them by position. Arrays are written with square brackets.
const fruits = ["apple", "banana", "cherry"];
const mixed = [42, "text", true, null, { x: 1 }, [1, 2]];
const empty = [];
console.log(fruits);
console.log(mixed);
console.log(fruits.length, empty.length);[ 'apple', 'banana', 'cherry' ]
[ 42, 'text', true, null, { x: 1 }, [ 1, 2 ] ]
3 0
Accessing elements
Each element has a numeric index, starting at 0. The last index is always length - 1. at() also accepts negative indexes counted from the end:
const colors = ["red", "green", "blue", "yellow"];
console.log(colors[0]);
console.log(colors[2]);
console.log(colors[colors.length - 1]);
console.log(colors.at(-1), colors.at(-2));
console.log(colors[10]); // no error, just undefinedred
blue
yellow
yellow blue
undefined
Changing elements
Arrays are mutable — even when declared with const, you can change their contents:
const scores = [70, 85, 90];
scores[0] = 75; // replace
scores[3] = 100; // add at the end
console.log(scores);
scores.push(60); // add at the end (preferred)
console.log(scores, scores.length);
const last = scores.pop(); // remove from the end
console.log(last, scores);[ 75, 85, 90, 100 ]
[ 75, 85, 90, 100, 60 ] 5
60 [ 75, 85, 90, 100 ]
Warning: Assigning to an index far beyond the end, such as
scores[50] = 1, creates "holes" of empty slots. Usepushto add elements.
Looping over an array
The for…of loop visits each element in order. When you also need the index, use entries() or a classic for loop:
const tasks = ["plan", "build", "test"];
for (const task of tasks) {
console.log("-", task);
}
for (const [i, task] of tasks.entries()) {
console.log(`${i + 1}. ${task}`);
}
tasks.forEach((task, i) => console.log(i, task.toUpperCase()));- plan
- build
- test
1. plan
2. build
3. test
0 PLAN
1 BUILD
2 TEST
Arrays are objects
typeof reports arrays as "object". Use Array.isArray() to check for an array:
const list = [1, 2, 3];
console.log(typeof list);
console.log(Array.isArray(list), Array.isArray({ length: 3 }));object
true false
Like other objects, arrays are copied by reference. To make an independent copy, spread it into a new array:
const a = [1, 2, 3];
const b = a; // same array
const c = [...a]; // a new copy
b.push(4);
console.log(a, c);
console.log(a === b, a === c);[ 1, 2, 3, 4 ] [ 1, 2, 3 ]
true false
Other ways to create arrays
| Code | Result |
|---|---|
[1, 2, 3] |
literal — the usual way |
Array.of(7) |
[7] |
new Array(3) |
three empty slots (confusing — avoid) |
Array.from("abc") |
['a', 'b', 'c'] |
Array.from({ length: 3 }, (_, i) => i * 2) |
[0, 2, 4] |
"a,b".split(",") |
['a', 'b'] |
Arrays of objects
Real data is often an array of objects — rows from a table, results from an API:
const people = [
{ name: "Aiko", age: 31 },
{ name: "Bruno", age: 25 },
];
console.log(people[1].name);
console.table(people);Bruno
┌─────────┬─────────┬─────┐
│ (index) │ name │ age │
├─────────┼─────────┼─────┤
│ 0 │ 'Aiko' │ 31 │
│ 1 │ 'Bruno' │ 25 │
└─────────┴─────────┴─────┘
The following chapters cover the many array methods for adding, removing, searching, sorting and transforming elements.
Test yourself
What is the index of the last element in an array of length 5?
- 5
- 4
- -1
- 0
How do you reliably check whether x is an array?
typeof x === "array"x instanceof ObjectArray.isArray(x)x.length > 0
Given const a = [1]; const b = a; b.push(2);, what is a?
- [1]
- [1, 2]
- [2]
- An error because a is const