Array basics

Topic 1 of 4 in Arrays8 min readBeginnerFree course

Overview

An array is an ordered list of values. Items can be of any type, and the list can grow or shrink. Use an array whenever you have many of the same kind of thing: a list of topics, the items in a cart, the rows of a table.

JavaScript
const topics = ['Loops', 'Functions', 'Objects'];
topics.length;  // 3
topics[0];      // 'Loops'  — indexes start at 0
topics.at(-1);  // 'Objects' — negative counts from the end

Each item’s position is its index. The first item is at index 0, so the last is at length - 1. Reading an index that doesn’t exist gives undefined, not an error.

Creating arrays

JavaScript
const empty = [];
const mixed = ['text', 42, true, null, { a: 1 }, [1, 2]]; // any types, even arrays
const filled = Array(3).fill(0);       // [0, 0, 0]
const range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
const letters = Array.from('abc');      // ['a', 'b', 'c']

In practice most arrays hold items of one kind (all strings, or all user objects). That makes them easy to loop over and process.

Changing items

Assign to an index to replace an item:

JavaScript
const colours = ['red', 'green', 'blue'];
colours[1] = 'yellow';   // ['red', 'yellow', 'blue']

An array declared with const can still have its items changed — const only stops you assigning a whole new array to the name.

Adding and removing

An array of three topics with indexes 0 to 2. At the start, unshift adds an item and shift removes one. At the end, push adds and pop removes. Below, slice(1, 3) copies 20 and 30 into a new array leaving nums unchanged, while splice(1, 2) removes 20 and 30 from nums itself.

JavaScript
topics.push('Arrays');      // add to the end      → returns the new length
topics.pop();               // remove from the end → returns the removed item
topics.unshift('Basics');   // add to the start
topics.shift();             // remove from the start

push and unshift can add several items at once: topics.push('A', 'B').

push/pop are quick. unshift/shift have to renumber every other item, so on very large arrays they’re slower — something to know, rarely something to worry about.

Stacks and queues

These pairs map onto two classic patterns:

  • A stack (last in, first out — like a pile of plates) uses push and pop. Your browser’s Back button works this way.
  • A queue (first in, first out — like a line at a counter) uses push and shift.
JavaScript
const history = [];
history.push('/home');
history.push('/courses');
history.pop(); // '/courses' — go back

slice vs splice

Their names are confusingly similar, but they do very different things.

slice(start, end) returns a copy of part of the array and leaves the original alone. Like the string method, it stops before end:

JavaScript
const nums = [10, 20, 30, 40];
nums.slice(1, 3); // [20, 30]
nums.slice(2);    // [30, 40]   — to the end
nums.slice(-2);   // [30, 40]   — last two
nums.slice();     // [10, 20, 30, 40] — a full copy

splice(start, deleteCount, ...items) changes the array itself — removing and/or inserting items at a position:

JavaScript
nums.splice(1, 2);          // removes 20 and 30 → nums is [10, 40]
nums.splice(1, 0, 15, 25);  // inserts → [10, 15, 25, 40]
nums.splice(0, 1, 5);       // replaces 10 with 5 → [5, 15, 25, 40]

splice returns an array of the items it removed.

Mutating or not? push, pop, shift, unshift, splice, sort, reverse and fill change the array. slice, map, filter, concat, spread, toSorted, toReversed and toSpliced give you a new one.

Knowing which is which avoids a whole family of bugs, especially when an array is shared between several parts of your program.

Finding things

JavaScript
const list = ['a', 'b', 'c'];
list.includes('b');  // true
list.indexOf('c');   // 2
list.indexOf('z');   // -1 (not found)
list.lastIndexOf('a'); // 0
Array.isArray(list); // true

includes and indexOf compare with ===, so they work well for strings and numbers but can’t find an object by its contents:

JavaScript
const users = [{ id: 1 }];
users.includes({ id: 1 }); // false — a different object

For that, use find or findIndex with a callback — covered in the next topic.

Combining and joining

JavaScript
const a = [1, 2];
const b = [3, 4];
a.concat(b);          // [1, 2, 3, 4]
[...a, ...b];         // [1, 2, 3, 4] — the modern way

['2026', '12', '03'].join('-'); // '2026-12-03'
['a', 'b'].join('');            // 'ab'
['a', 'b'].join();              // 'a,b' — comma by default

Length

length is always one more than the highest index. You can even set it, which truncates the array:

JavaScript
const items = [1, 2, 3, 4, 5];
items.length = 2;   // items is now [1, 2]
items.length = 0;   // a quick way to empty an array in place

Assigning far beyond the end creates “holes” (empty slots), which behave oddly. Avoid items[100] = x on a short array; use push instead.

Nested arrays

Arrays can hold other arrays, which is a simple way to represent grids:

JavaScript
const board = [
  ['X', 'O', 'X'],
  ['O', 'X', 'O'],
  ['', '', 'X'],
];
board[0][2]; // 'X' — row 0, column 2
board.flat(); // one long array of all nine cells

Arrays are objects

typeof [] is 'object'. Like other objects, arrays are stored by reference:

JavaScript
const original = [1, 2, 3];
const alias = original;
alias.push(4);
original; // [1, 2, 3, 4] — same array

const copy = [...original];
copy.push(5);
original; // [1, 2, 3, 4] — unaffected

Use Array.isArray(value) — not typeof — to check whether something is an array.

Exercise

Last three

Write lastThree(list) that returns a new array with the last three items (or fewer if the list is shorter). Then write insertAt(list, index, item) that returns a new array with item inserted at index, without changing list.

JavaScript
function lastThree(list) {
  // your code here
}

function insertAt(list, index, item) {
  // your code here
}

Summary

  • Arrays are ordered lists; indexes start at 0 and the last is length - 1.
  • push/pop work at the end, unshift/shift at the start.
  • slice copies part of an array; splice changes the array in place.
  • includes, indexOf and Array.isArray answer simple questions.
  • Arrays are objects: they are copied and compared by reference.