Hone

Lessons · JavaScript · push

Adding to the end

arr.push(x) adds x to the end of the array in place and returns the new length. unshift adds to the front.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Building a list of results, queueing work, collecting matches: push is the everyday way an array grows.

How to think about it

Call push on its own line; its return value is the length, not the array. When you want a new array instead of changing this one, spread: [...arr, x].

Worked example

const xs = [1, 2];
Two items.
const n = xs.push(3);
Adds 3, returns the new length.
console.log(xs, n);
[ 1, 2, 3 ] 3.
xs.unshift(0);
Adds to the front.
console.log(xs);
[ 0, 1, 2, 3 ].

Your turn

Add a job to the end of the queue.

queue.(job);

The trap

const ys = xs.push(4) stores the number 4, the new length, not the array. push changes xs and returns a count.

Practise push on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.