JavaScript Arrays: push, pop, splice, sort and More
An array is an ordered list of values written in square brackets: ["apple", "banana"]. Arrays grow and shrink as needed, can hold any mix of types, and are the most common way to store a collection in JavaScript.
Reading items
Positions start at 0. fruits[0] is the first item and fruits.length is the count, so the last item is fruits[fruits.length - 1], or more simply fruits.at(-1). Reading a position that does not exist returns undefined rather than throwing. indexOf(x) finds a position, returning -1 when absent, and includes(x) answers yes or no.
Adding and removing
These methods change the array in place:
push(x)adds to the end andpop()removes from the end.unshift(x)adds to the front andshift()removes from the front.splice(start, deleteCount, ...items)removes and/or inserts anywhere.splice(1, 0, "mango")deletes nothing and inserts at position 1.
pop(), shift() and splice() return what they removed, which the example prints.
Expected output
["kiwi", "apple", "banana", "cherry"] 4 kiwi cherry 2 cherry kiwi ["apple", "banana"] ["apple", "mango", "banana"] true apple | mango | banana [1, 10, 5] [1, 5, 10] true [1, 5]
Copying and combining
slice(start, end) returns a new array with part of the original, and slice() with no arguments copies the whole array. The spread syntax [...nums] also makes a shallow copy, and [...a, ...b] joins arrays. join(" | ") turns an array into a single string.
The sort trap
sort() sorts in place, and by default it converts items to strings and compares them alphabetically. That is why [10, 1, 5].sort() gives [1, 10, 5]: the string "10" comes before "5". For numbers, pass a compare function: sort((a, b) => a - b) sorts ascending and (a, b) => b - a descending. The example sorts copies made with spread so the original stays unchanged; newer engines also offer toSorted(), which returns a sorted copy directly.
Checking for arrays
typeof [] is "object", so use Array.isArray(value) when you need to know whether something is an array.
Common mistakes
- Sorting numbers without a compare function.
- Confusing
slice(copies, original unchanged) withsplice(modifies the original). - Assuming
const arr = []cannot change.constprevents reassigning the name, not pushing items.
Summary
push/popwork at the end,unshift/shiftat the front,spliceanywhere.sliceand spread make copies;joinbuilds a string.- Default
sort()compares strings; pass(a, b) => a - bfor numbers.
Quiz: Arrays