After this lesson you can keep a list of things in one variable, pick out any item, change it, walk through the whole list, and avoid the classic trap of accidentally changing an array you thought you had copied.
What an array is
So far each variable has held one value. Real programs deal with lists: the names of students, the prices in a basket, the lines of a file. An array holds many values in order, written inside square brackets and separated by commas.
const fruits = ["apple", "banana", "cherry"];
const mixed = [42, "hello", true, null]; // any types, even mixed
const empty = [];Arrays can hold anything, including other arrays and objects. In practice you will usually keep one kind of thing in each array, because that makes the code that processes it simpler.
Indexes start at zero
Each item has a position called an index. Counting starts at 0, not 1. You read an item with square brackets after the array name.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits[2]); // cherry
console.log(fruits[3]); // undefined, there is no fourth item
console.log(fruits.length); // 3The length property is the number of items, so the last index is always length - 1. Modern JavaScript also has at(), which accepts negative numbers to count from the end: fruits.at(-1) is "cherry", and fruits.at(-2) is "banana". Reading an index that does not exist is not an error; you simply get undefined.
Changing an array
Assign to an index to replace an item. Assigning to the next free index adds one.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry"; // replace
fruits[3] = "date"; // add at the end
log(fruits.join(", "));
log("length:", fruits.length);
fruits.length = 2; // shrinking length cuts items off
log(fruits.join(", "));
</script>Notice that you can change items of an array declared with const. The const keyword stops you from pointing the name at a different array; it does not freeze the contents. This surprises many beginners, and it comes back in the lesson on objects.
Writing to a far-away index such as fruits[10] = "x" leaves empty gaps in between. Avoid it. Add items with push, covered in adding, removing and searching arrays.
Looping over an array
The cleanest way to visit every value is for...of:
const scores = [8, 5, 9];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(total); // 22You can still use a classic for loop with an index when you need the position:
const names = ["Asha", "Ben", "Chen"];
for (let i = 0; i < names.length; i++) {
console.log(i, names[i]);
}
// 0 Asha
// 1 Ben
// 2 ChenThere is also names.forEach((name, i) => { ... }), which calls a function for each item. A limitation worth knowing: you cannot break out of forEach, while you can inside for...of. Do not use for...in on arrays; it loops over keys as strings and can include unexpected properties.
Arrays are references
This is the most important idea in the lesson. An array is an object, and a variable holding it really holds a reference to it, like an address. Copying the variable copies the address, not the list.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const original = [1, 2, 3];
const alias = original; // same array, two names
const copy = [...original]; // a new array with the same items
alias.push(4);
log("original:", original.join(","));
log("alias: ", alias.join(","));
log("copy: ", copy.join(","));
log("original === alias?", original === alias);
log("original === copy?", original === copy);
</script>The output shows original and alias both containing 1,2,3,4, while copy is untouched. Comparing two arrays with === also compares references, so two separate arrays with identical contents are not equal.
[...original] and original.slice() make a shallow copy: the new array is separate, but if its items are themselves arrays or objects, those inner items are still shared. For a full independent duplicate use structuredClone(original), available in all current browsers and in Node 17 and later.
Arrays of arrays
An item can be another array, which gives you a grid:
const grid = [
[1, 2, 3],
[4, 5, 6],
];
console.log(grid[1][2]); // 6, row 1, column 2Read the double index from left to right: first pick the row, then the item within it.
Useful checks
Array.isArray(x)tells you whetherxis an array.typeof []says"object", which is not helpful.arr.includes("apple")tells you whether a value is present.arr.join(", ")turns an array into a string.
Common mistakes
- Expecting the first item at index 1. The first item is
arr[0]. - Using
arr[arr.length]for the last item. That index is one past the end. Usearr[arr.length - 1]orarr.at(-1). - Thinking
const b = amakes a copy. It makes a second name for the same array, so changes through one name show up through the other. - Comparing arrays with
===and expecting equal contents to match. - Printing an array inside a string and being surprised:
"List: " + [1, 2]givesList: 1,2. Usejointo control the format.
Exercise
Create an array of five numbers. Write a loop that finds the largest number without using Math.max. Then make a copy of the array, change the first item in the copy, and show that the original did not change.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const numbers = [4, 19, 7, 12, 3];
let largest = numbers[0];
for (const n of numbers) {
if (n > largest) largest = n;
}
log("largest:", largest);
const copy = [...numbers];
copy[0] = 100;
log("original:", numbers.join(","));
log("copy:", copy.join(","));
</script>Key points
- An array is an ordered list. Items are read by index, and the first index is 0.
- length tells you how many items there are, and the last item is at index length - 1 (or use at(-1)).
- Assigning to a new index or changing an item mutates the array in place.
- for...of loops over the values; forEach calls a function for each one.
- Arrays are objects, so copying with = copies the reference, not the list. Use [...arr] for a shallow copy.