JavaScript Arrays: Create, Read and Loop Through Lists
Learn how to create JavaScript arrays, access items by index, add values and loop through a list with for...of.
Create an array
An array stores an ordered list of values. Each item has a zero-based index, so the first item is at index 0.
const colors = ["blue", "green", "orange"];
console.log(colors[0]); // "blue"
console.log(colors.length); // 3
Add or update items
Use push() to add an item to the end. Use an index when you need to replace an existing item.
colors.push("purple");
colors[1] = "teal";
Loop through a list
A for...of loop reads each value in order. It works well when you want to perform the same action for every item.
for (const color of colors) {
console.log(color);
}
Use common array methods
includes() checks whether an array contains a value. map() builds a new array by transforming each item, and filter() builds a new array from items that pass a condition.
const scores = [58, 82, 91];
const hasHighScore = scores.includes(91);
const doubled = scores.map(score => score * 2);
const passing = scores.filter(score => score >= 70);
map() and filter() leave the original array unchanged. By contrast, push() changes the array it is called on.
Array questions
Why does the first array item use index zero?
JavaScript array indexes count from zero, so for an array with three items, the valid indexes are 0, 1, and 2. The item count is available from the length property.
How do I add an item to the end?
Call push(value). It updates the existing array and returns its new length.