JavaScript Arrays
JavaScript arrays store ordered lists of values in one variable. An array can hold any mix of types, grows automatically and comes with dozens of useful methods.
Creating and Reading Arrays
Write arrays with square brackets. Indexes start at 0. length tells you how many items there are, and at(-1) returns the last item.
const fruits = ["mango", "apple", "banana"];
console.log(fruits[0]);
console.log(fruits.length);
console.log(fruits.at(-1));
fruits[1] = "kiwi";
console.log(fruits.join(", "));mango 3 banana mango, kiwi, banana
Adding and Removing Items
- push(x) adds to the end
- pop() removes from the end
- unshift(x) adds to the start
- shift() removes from the start
- splice(index, count, ...items) removes and/or inserts anywhere
const queue = ["a", "b"];
queue.push("c");
queue.unshift("z");
console.log(queue.join(" "));
queue.pop();
queue.shift();
console.log(queue.join(" "));
const letters = ["a", "b", "c", "d"];
letters.splice(1, 2, "X"); // remove 2 items at index 1, insert "X"
console.log(letters.join(" "));z a b c a b a X d
Non-Mutating Versions (ES2023)
Methods like sort, reverse and splice change the original array. ES2023 added toSorted, toReversed, toSpliced and with, which return a new array and keep the original untouched. This is safer, especially in React.
const nums = [3, 1, 2];
const sorted = nums.toSorted((a, b) => a - b);
console.log(sorted.join(","), "| original:", nums.join(","));
console.log(nums.with(0, 99).join(","));1,2,3 | original: 3,1,2 99,1,2
Copying and Combining Arrays
The spread operator ... copies or merges arrays. This is a shallow copy: nested objects are still shared.
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b, 5];
const copy = [...a];
copy.push(100);
console.log(merged.join(","), "|", a.join(","));
console.log(merged.includes(4), merged.indexOf(5));1,2,3,4,5 | 1,2 true 4
Frequently asked questions
How do I remove a specific item from an array in JavaScript?
Find its index with indexOf and call splice(index, 1), or create a new array with filter(x => x !== item).
How do I check if a value is an array?
Use Array.isArray(value). typeof returns "object" for arrays, so it cannot tell them apart.
How do I sort numbers correctly in JavaScript?
Pass a compare function: nums.sort((a, b) => a - b). Without it, sort compares values as strings, so 10 comes before 9.