Arrays in JavaScript
Introduction
An array is an ordered list of values—scores, tags, cart lines, or API rows. Arrays are objects specialized for numeric indices and .length. This chapter introduces creation, indexing, length, and basic iteration—the foundation for sorting, mapping, and filtering later.
Prerequisites
Creating Arrays
// Array literal
const fruits = ["apple", "banana", "orange"];
// Constructor (rare for literals)
const numbers = new Array(3);
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
console.log(fruits);
console.log(numbers);Prefer literals [] in application code.
Indexing and length
Zero-based indexes; length is one past the last index:
// Access and update by index
const colors = ["red", "green", "blue"];
console.log(colors[0]);
console.log(colors.length);
colors[1] = "lime";
console.log(colors);Adding Items
// push and pop at end
const queue = ["a", "b"];
queue.push("c");
console.log(queue);
const last = queue.pop();
console.log(last, queue);unshift / shift work at the start (slower on large arrays).
Iteration
// for...of and forEach
const scores = [88, 92, 75];
for (const score of scores) {
console.log(score);
}
scores.forEach((score, index) => {
console.log(index, score);
});Arrays Are Objects
// typeof array
console.log(typeof []);
console.log(Array.isArray([]));Do not confuse arrays with plain objects—use Array.isArray when unsure.
Multi-Dimensional Arrays
// Matrix as array of arrays
const grid = [
[1, 2, 3],
[4, 5, 6],
];
console.log(grid[1][2]);Mini Example: Todo List
// Simple in-memory todo list
const todos = ["Write docs", "Review PR"];
todos.push("Ship feature");
for (let i = 0; i < todos.length; i++) {
console.log(`${i + 1}. ${todos[i]}`);
}FAQ
Are arrays fixed size?
No—length changes as you add/remove elements (within memory limits).
Can arrays hold mixed types?
Yes—[1, "two", true, { ok: 1 }] is valid, but consistent element types improve clarity.
What are sparse arrays?
Missing indexes create holes—avoid unless you know the behavior you need.
What comes next?
Array mutation, search, sorting, and map / filter / reduce in following chapters.