Adding and Removing Items

Grade 7, page 5 of 14. A one-minute read.

Arrays come with built-in methods for adding and removing items at either end. There are four, and they come in pairs:

MethodWhat it doesGives back
push(item)Adds item(s) to the endThe new length
pop()Removes the last itemThe removed item
unshift(item)Adds item(s) to the startThe new length
shift()Removes the first itemThe removed item
JavaScript
const queue = ["Mia", "Omar"];

queue.push("Zoe");
console.log(queue);

queue.unshift("Sam");
console.log(queue);

const last = queue.pop();
console.log(`Removed from the end: ${last}`);
console.log(queue);

const first = queue.shift();
console.log(`Removed from the start: ${first}`);
console.log(queue);

It prints

[ 'Mia', 'Omar', 'Zoe' ]
[ 'Sam', 'Mia', 'Omar', 'Zoe' ]
Removed from the end: Zoe
[ 'Sam', 'Mia', 'Omar' ]
Removed from the start: Sam
[ 'Mia', 'Omar' ]
Think of it like thisThe queue at the bank

Picture a queue at the bank. When a new customer arrives, they join at the back of the line: that's push. When the cashier is ready, they serve the person at the front: that's shift. If the person at the back gets bored and leaves, that's pop. And if someone rude pushes in at the very front, well... that's unshift. (Don't be an unshift in real life.)

TipThe easy one to remember

push and pop work on the end of the array, and they're by far the most common. If you only remember one method from this lesson, make it push. You'll use it constantly to build up lists.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning