An array is an ordered list of values stored under one name. A class roster, a playlist, the scores on a test, the squares on a game board: whenever you have "several of the same kind of thing," you want an array.
Without an array, a list of cars needs one variable per car:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
That works for 3 cars. Now imagine 300, or looping through them to find one. An array keeps them all under one name, and a number (the index) picks out each one.
Square brackets, with values separated by commas:
const fruits = ["apple", "banana", "cherry"];
const scores = [88, 92, 75, 100];
const empty = [];
Each value is called an element. Arrays can hold any type, and even mix types, though in practice most arrays hold one kind of thing.
Spaces and line breaks do not matter, so long arrays are often written one element per line. You can also start with an empty array and fill it in by position:
const cars = [
"Saab",
"Volvo",
"BMW"
];
const pets = [];
pets[0] = "cat";
pets[1] = "dog";
console.log(pets);
You will also see new Array("Saab", "Volvo", "BMW"). It builds the same array, but [] is shorter, easier to read, and avoids a trap covered in Array Constructor. Arrays are usually declared with const; Array const explains why that still lets you change them.
const fruits = ["apple", "banana", "cherry"];
// 0 1 2
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
console.log(fruits[3]); // undefined (no element there)
console.log(fruits.length); // 3
console.log(fruits[fruits.length - 1]); // "cherry"
console.log(fruits.at(-1)); // "cherry" (modern shortcut)
length - 1. An array of 3 elements has indexes 0, 1, and 2. This off-by-one relationship is behind most array bugs.
const colors = ["red", "green", "blue"];
colors[1] = "lime"; // replace
colors.push("purple"); // add to the end
console.log(colors);
colors[10] = "gold", stretches the array to length 11 and leaves empty "holes" in positions 4 to 9. Use push to add to the end.
Another way to add to the end: assign to index length. Since the last index is always length - 1, index length is the first empty spot:
const fruits = ["Banana", "Orange"];
fruits[fruits.length] = "Lemon";
console.log(fruits);
An array turns into text automatically whenever JavaScript needs a string, for example when you join it to other text. toString() does the same thing on purpose. Both give the values separated by commas, with no brackets or quotes:
const cars = ["Saab", "Volvo", "BMW"];
console.log(cars.toString());
console.log("Cars: " + cars);
console.log(JSON.stringify(cars));
JSON.stringify (from JS Object Display) keeps the brackets and quotes, so you can see exactly what is inside. That matters on a web page, where putting an array into an element with document.getElementById("demo").innerHTML = cars (find the element with id "demo", then set its content) shows the comma version.
const scores = [88, 92, 75];
// When you need the position
for (let i = 0; i < scores.length; i++) {
console.log(`Test ${i + 1}: ${scores[i]}`);
}
// When you only need the values
let total = 0;
for (const s of scores) {
total += s;
}
console.log(`Average: ${(total / scores.length).toFixed(1)}`);
console.log(typeof [1, 2, 3]); // "object" (not helpful)
console.log(Array.isArray([1, 2, 3])); // true (use this instead)
Like other objects, arrays are passed and assigned by reference:
const a = [1, 2, 3];
const b = a; // same array, two names
const c = [...a]; // a real copy, using spread
b.push(4);
console.log(a); // [1, 2, 3, 4] changed through b
console.log(c); // [1, 2, 3] the copy is independent
Another way to check is instanceof, which asks "was this made by Array?":
console.log([1, 2] instanceof Array); // true
console.log({} instanceof Array); // false
Some languages have "associative arrays" (also called hashes) with named positions, like person["firstName"]. JavaScript arrays do not. Arrays always use numbered indexes:
const person = [];
person["firstName"] = "John";
person["age"] = 46;
console.log(person.length); // 0 !
console.log(person[0]); // undefined
person["firstName"] = "John" on an array, but it stores it as a plain object property. The array part stays empty: length is 0 and array methods ignore it. If you want names, use an object.
| Use | When the names are | Example |
|---|---|---|
| Array | numbers (positions in a list) | scores[2] |
| Object | text (names of details) | person.firstName |
The most common real-world shape: a list where each item has several details.
const students = [
{ name: "Ava", grade: 10 },
{ name: "Ben", grade: 11 },
{ name: "Cal", grade: 10 }
];
console.log(students[1].name); // "Ben"
console.log(students.length); // 3
const board = [
["X", "O", "X"],
[" ", "X", "O"],
["O", " ", "X"]
];
console.log(board[1][2]); // "O" (row 1, column 2)
Read board[1][2] from left to right: take row 1, then take position 2 from that row.
An element can be any value: a string, a number, an object, another array, even a function:
const tools = [Math.max, x => x * 2];
console.log(tools[0](3, 7)); // call the function stored at index 0
console.log(tools[1](5));
Objects and arrays also nest inside each other. Here an object holds an array of objects, and each of those holds another array. Use one loop per level:
const garage = {
owner: "John",
cars: [
{ name: "Ford", models: ["Fiesta", "Focus"] },
{ name: "Fiat", models: ["500", "Panda"] }
]
};
for (const car of garage.cars) {
for (const model of car.models) {
console.log(car.name, model);
}
}
for (let i in arr). It works, but for...in was made for object properties: it hands you the indexes as strings ("0", "1"), and can pick up extra properties. Use for...of or a counting for loop. Array Iterations shows the details.
| Array Constructor | Other ways to create arrays, and a trap to avoid |
| Array Methods | Adding, removing, joining, slicing |
| Array Search | Finding values and positions |
| Array Sort | Putting elements in order (with a famous gotcha) |
| Array Iterations | map, filter, reduce and friends |
| Array const | What const does and does not protect |
An array has a length of 5. What is the index of its last element?
54-16length - 1. (arr.at(-1) also gets the last element, but arr[-1] is undefined.)What does this log?
const p = [];
p["name"] = "Ava";
console.log(p.length);
0. Arrays have no named indexes. "name" becomes an ordinary object property, so the array itself is still empty. Use an object for named values.What does this log?
const a = [1, 2];
const b = a;
b.push(3);
console.log("Total: " + a);
Total: 1,2,3. b is the same array as a, so pushing through b changes a. Joined to a string, the array turns into comma-separated text.[...songs], change the copy, and confirm the original is untouched