SKU // 64

JavaScript Arrays

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.

// Why Use Arrays?

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.

// Creating an Array

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);
["cat", "dog"]

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.

// Index: Positions Start at 0

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)
apple cherry undefined

// Length and the Last Element

console.log(fruits.length);                 // 3
console.log(fruits[fruits.length - 1]);     // "cherry"
console.log(fruits.at(-1));                // "cherry"  (modern shortcut)
Note
The last index is always length - 1. An array of 3 elements has indexes 0, 1, and 2. This off-by-one relationship is behind most array bugs.

// Changing and Adding Elements

const colors = ["red", "green", "blue"];

colors[1] = "lime";        // replace
colors.push("purple");     // add to the end

console.log(colors);
["red", "lime", "blue", "purple"]
Watch out
Assigning far past the end, like 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);
["Banana", "Orange", "Lemon"]

// Displaying an Array

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));
Saab,Volvo,BMW Cars: Saab,Volvo,BMW ["Saab","Volvo","BMW"]

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.

// Looping Through an Array

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)}`);
Test 1: 88 Test 2: 92 Test 3: 75 Average: 85.0

// Arrays Are Objects

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
[1, 2, 3, 4] [1, 2, 3]

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

// No Named Indexes

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
Trap: named indexes
JavaScript does not stop you from writing 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.
UseWhen the names areExample
Arraynumbers (positions in a list)scores[2]
Objecttext (names of details)person.firstName

// Arrays of Objects

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

// Arrays of Arrays (Grids)

const board = [
  ["X", "O", "X"],
  [" ", "X", "O"],
  ["O", " ", "X"]
];

console.log(board[1][2]);   // "O"  (row 1, column 2)
O

Read board[1][2] from left to right: take row 1, then take position 2 from that row.

// Arrays Can Hold Anything

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));
7 10

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);
  }
}
Ford Fiesta Ford Focus Fiat 500 Fiat Panda
Avoid for...in on arrays
Some tutorials (including W3Schools' nested example) loop over arrays with 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.

// The Road Ahead

Array ConstructorOther ways to create arrays, and a trap to avoid
Array MethodsAdding, removing, joining, slicing
Array SearchFinding values and positions
Array SortPutting elements in order (with a famous gotcha)
Array Iterationsmap, filter, reduce and friends
Array constWhat const does and does not protect

// Quick Check

An array has a length of 5. What is the index of its last element?

  1. 5
  2. 4
  3. -1
  4. 6
Show answer
B. Indexes start at 0, so 5 elements use indexes 0 to 4. The last index is always length - 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);
Show answer
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);
Show answer
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.

// Try It

  1. Click Open Playground. Put your five favorite songs in the array, then print the first and last using two different methods
  2. Replace the third song, then push a new one. Print the length
  3. Make a real copy with [...songs], change the copy, and confirm the original is untouched
  4. Build a 3 by 3 grid of numbers and print the center value
// Video Walkthroughs
Last updated: Oct 10, 2026, 1:41 AM ET