Codiqo

Learn JavaScript · lesson 26 of 60 · about 7 minutes

Adding and Removing Items

Let the visitor sign the guestbook: add to the end with push, and keep the 5 newest names by removing from the front with shift.

What you'll learn

  • Add to the end with push()
  • Remove from the end with pop()
  • Work at the front with shift() and unshift()

Signing the guestbook

When a visitor signs, their name goes on the end of guests with push. The box only has room for the 5 newest names, so while there are more than 5, the oldest leaves from the front with shift. join(", ") turns the names into one line of text.

Both ends

| Method | Where | Does |
|---|---|---|
| push(x) | end | Adds x |
| pop() | end | Removes and returns the last item |
| unshift(x) | front | Adds x |
| shift() | front | Removes and returns the first item |

A queue at the shop

const queue = ["Ada"];
queue.push("Bo");
queue.push("Cy");
queue.unshift("VIP");
console.log(queue.join(", "));
const served = queue.shift();
const left = queue.pop();
console.log(served, left, queue.join(", "));

Output

VIP, Ada, Bo, Cy
VIP Cy Ada, Bo

Tip

slice(start, end) copies part of an array without changing it, just like it does for strings.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.