An array is an ordered list of values. It is how you store a to-do list, a set of prices, or the results of a search.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits); // → ["apple", "banana", "cherry"]
console.log(fruits.length); // → 3
Square brackets create the array, and items are separated by commas. An array can hold any values, even mixed types, though lists of one kind of value are easier to work with.
Reading items by index
Positions are called indexes, and they start at 0.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // → apple
console.log(fruits[2]); // → cherry
console.log(fruits[5]); // → undefined
console.log(fruits.at(-1)); // → cherry (last item)
console.log(fruits[fruits.length - 1]); // → cherry
at(-1) counts from the end, which avoids the length - 1 calculation.
Changing items
const fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry";
console.log(fruits); // → ["apple", "blueberry", "cherry"]
You can change items of a const array. What const prevents is pointing the name at a different array, see let and const.
Length
length is always one more than the last index. Setting it shorter cuts the array.
const letters = ["a", "b", "c", "d"];
letters.length = 2;
console.log(letters); // → ["a", "b"]
Creating arrays
const empty = [];
const numbers = [1, 2, 3];
const mixed = ["text", 42, true, null, [1, 2]];
const filled = new Array(3).fill(0);
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(filled); // → [0, 0, 0]
console.log(range); // → [1, 2, 3, 4, 5]
console.log(mixed.length); // → 5
Arrays are objects
console.log(typeof []); // → object
console.log(Array.isArray([])); // → true
console.log(Array.isArray("abc")); // → false
Use Array.isArray() to check for an array, because typeof cannot tell arrays from other objects.