Array basics
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.
const topics = ['Loops', 'Functions', 'Objects'];
topics.length; // 3
topics[0]; // 'Loops' — indexes start at 0
topics.at(-1); // 'Objects' — negative counts from the endEach 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
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:
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
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 startpush 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
pushandpop. Your browser’s Back button works this way. - A queue (first in, first out — like a line at a counter) uses
pushandshift.
const history = [];
history.push('/home');
history.push('/courses');
history.pop(); // '/courses' — go backslice 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:
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 copysplice(start, deleteCount, ...items) changes the array itself — removing and/or inserting items at a position:
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,reverseandfillchange the array.slice,map,filter,concat, spread,toSorted,toReversedandtoSplicedgive 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
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); // trueincludes and indexOf compare with ===, so they work well for strings and numbers but can’t find an object by its contents:
const users = [{ id: 1 }];
users.includes({ id: 1 }); // false — a different objectFor that, use find or findIndex with a callback — covered in the next topic.
Combining and joining
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 defaultLength
length is always one more than the highest index. You can even set it, which truncates the array:
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 placeAssigning 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:
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 cellsArrays are objects
typeof [] is 'object'. Like other objects, arrays are stored by reference:
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] — unaffectedUse Array.isArray(value) — not typeof — to check whether something is an array.
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.
function lastThree(list) {
// your code here
}
function insertAt(list, index, item) {
// your code here
}function lastThree(list) {
return list.slice(-3);
}
function insertAt(list, index, item) {
return [...list.slice(0, index), item, ...list.slice(index)];
}Summary
- Arrays are ordered lists; indexes start at 0 and the last is
length - 1. push/popwork at the end,unshift/shiftat the start.slicecopies part of an array;splicechanges the array in place.includes,indexOfandArray.isArrayanswer simple questions.- Arrays are objects: they are copied and compared by reference.