Changing arrays: push, pop, splice
The first four methods of this lesson change the array they are called on and return something else: an item that came out or the new length. That split is the source of most of the surprises, because a line like stack.push(item) looks like it gives back the list and in fact gives back a number. JavaScript has no method that both changes an array and returns it.
The lesson takes the four ends first, then splice, which does all of the same work at any position, and closes with the return value of each call on the same array. The copying methods of the next lessons return a new array instead, and the difference is easier to keep straight once the old ones are known.
push and pop at the end
push adds one or more items at the end and returns the new length, pop takes the last item off and returns it. Both work on the last position, so neither has to move anything else, and both are cheap however long the array is.
const stack = ['a', 'b'];
console.log('push returns the new length:', stack.push('c'));
console.log('the array:', JSON.stringify(stack));
console.log('pop returns the item:', stack.pop());
console.log('the array:', JSON.stringify(stack));
console.log('pop on an empty array:', [].pop());
console.log('push takes several items:', stack.push('x', 'y'), JSON.stringify(stack));
node end.js
push returns the new length: 3
the array: ["a","b","c"]
pop returns the item: c
the array: ["a","b"]
pop on an empty array: undefined
push takes several items: 4 ["a","b","x","y"]
The number 3 is the length after the push, not the item that was added, and the array had to be printed separately to see the result. pop on an empty array returns undefined and does not throw, so a loop that empties a stack can read the result and stop. The last line is push with two arguments, which adds both and still returns one number.
shift and unshift at the start
unshift adds at the front and shift removes the first item, with the same return values as the pair at the end. The work is different: every remaining item has to move one position to the right or to the left, so both cost time in proportion to the length. The program shows the movement through the indexes.
const queue = ['b', 'c'];
console.log('unshift returns the new length:', queue.unshift('a'));
console.log('the array:', JSON.stringify(queue));
console.log('shift returns the item:', queue.shift());
console.log('the array:', JSON.stringify(queue));
console.log('shift on an empty array:', [].shift());
const reindexed = ['a', 'b', 'c'];
reindexed.shift();
console.log('after a shift the indexes move:', reindexed.map((value, index) => `${index}:${value}`).join(','));
node start.js
unshift returns the new length: 3
the array: ["a","b","c"]
shift returns the item: a
the array: ["b","c"]
shift on an empty array: undefined
after a shift the indexes move: 0:b,1:c
After the shift the item that was at index 1 is at index 0, which is the movement the method does internally and the reason it is slower than pop. A queue built on shift is correct and costs more with every item that is taken out; the larger the list and the more often it happens, the more it shows. For a queue of thousands of items an index that only moves forward, or a Map, is the better tool.
splice: remove, insert, replace
splice(start, deleteCount, ...items) does the work of all four methods at any position. It removes deleteCount items from start, puts the items that follow into that place, and returns an array of the items it removed, which is empty when it only inserts. A negative start counts from the end.
const letters = ['a', 'b', 'c', 'd'];
const removed = letters.splice(1, 2);
console.log('splice(1, 2) returns:', JSON.stringify(removed));
console.log('what is left:', JSON.stringify(letters));
const nothing = letters.splice(1, 0, 'x', 'y');
console.log('splice(1, 0, x, y) returns:', JSON.stringify(nothing));
console.log('what is left:', JSON.stringify(letters));
const replaced = letters.splice(0, 1, 'A');
console.log('splice(0, 1, A) returns:', JSON.stringify(replaced));
console.log('what is left:', JSON.stringify(letters));
console.log('a negative start counts from the end:', JSON.stringify(['a', 'b', 'c', 'd'].splice(-2)));
node splice.js
splice(1, 2) returns: ["b","c"]
what is left: ["a","d"]
splice(1, 0, x, y) returns: []
what is left: ["a","x","y","d"]
splice(0, 1, A) returns: ["a"]
what is left: ["A","x","y","d"]
a negative start counts from the end: ["c","d"]
Three calls and three answers: a removal gives the removed items, an insertion gives an empty array, and a replacement gives what it took out. The variable named nothing is that empty array and not undefined, which matters when the result is checked. The last line removed the last two items because a start of -2 counts from the end, and the same call without a delete count removes everything from the start to the end.
What each method returns
The five methods on one page make the return values easy to compare. Each of them changes the array and gives back something that is not the array, and that is the shape a caller has to expect.
const rows = [
['push', ['a'].push('b')],
['pop', ['a', 'b'].pop()],
['unshift', ['b'].unshift('a')],
['shift', ['a', 'b'].shift()],
['splice', ['a', 'b', 'c'].splice(1, 1)],
];
for (const [method, result] of rows) {
console.log(`${method} returned ${JSON.stringify(result)}`);
}
const items = ['a', 'b', 'c'];
console.log('each of them changes the array:', JSON.stringify(items.splice(1, 1)), JSON.stringify(items));
node returns.js
push returned 2
pop returned "b"
unshift returned 2
shift returned "a"
splice returned ["b"]
each of them changes the array: ["b"] ["a","c"]
Two numbers, two items and one array: push and unshift return a length, pop and shift return an item or undefined, and splice always returns an array. The last line prints the removed item and the array it was removed from, which is the pair a caller has to keep apart. A function that builds a list and returns the result of push returns a number, and that mistake is worth recognizing in code that looks right.
Exercises
- Empty the stack in end.js with a while loop that reads the result of pop. How many times does the body run for the final four items?
- In start.js, move the first item to the end with one shift and one push, then print the array. Why does the length not change?
- Remove the second item of an array of five and put two new items in its place with one splice call. What does it return, and how long is the array afterwards?
- Replace splice(1, 1) in returns.js with splice(1). Which line of the output changes and to what?
- Write a function take(array, count) that removes the first count items and returns them, with one call and no loop. Which of the five methods does the work?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
[1, 2].push(3)return?Answer
3, the new length
push returns the new length, and the array it changed has to be read separately.
-
What does
[1, 2].pop()return?Answer
2
pop removes and returns the last item, so the array is left with one item.
-
What does
[].pop()return?Answer
undefined
An empty array has no last item, and the method reports that with undefined instead of throwing.
-
What does this program print?
const a = ["b", "c"]; console.log(a.unshift("a"), a.join(""));Answer
3 abc
unshift returns the new length, and the item was added at the front.
-
Which pair of methods does the most work for every call?
Answer
shift and unshift, because every remaining item moves one index
The methods at the start reindex the whole array, and the methods at the end do not.
-
What does this program print?
const a = ["a", "b", "c", "d"]; console.log(JSON.stringify(a.splice(1, 2)), a.length);Answer
["b","c"] 2
Two items from index 1 came out, and the array kept the other two.
-
What does
splice(1, 0, "x")return?Answer
An empty array, because nothing was removed
With a delete count of zero the call only inserts, so the list of removed items is empty.
-
What does this program print?
const a = [1, 2, 3, 4]; a.splice(-2); console.log(a.join(","));Answer
1,2
A negative start counts from the end, and with no delete count everything from there is removed.
-
Why is a queue built with
shiftslower than one built with an index?Answer
Every shift moves the remaining items one position to the left
The reindexing is the cost, and it grows with the number of items left in the array.
-
What is the return value of
[1, 2, 3].splice(0, 1, "a", "b")?Answer
[1]
splice returns what it removed, which is the one item at index 0.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev