Skip to content

JavaScript Tutorial Arrays

JavaScript push, pop, shift and unshift

Lesson 64 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Four methods add or remove items at the ends of an array. All of them change the original array (they mutate it).

MethodEndActionReturns
push(x)endaddthe new length
pop()endremovethe removed item
unshift(x)startaddthe new length
shift()startremovethe removed item
script.js
JS
const queue = ["b", "c"];

queue.push("d");          // add to the end
console.log(queue);       // → ["b", "c", "d"]

queue.unshift("a");       // add to the start
console.log(queue);       // → ["a", "b", "c", "d"]

const last = queue.pop(); // remove from the end
console.log(last);        // → d

const first = queue.shift(); // remove from the start
console.log(first);       // → a
console.log(queue);       // → ["b", "c"]

Adding several items

script.js
JS
const list = [1];
list.push(2, 3, 4);
console.log(list); // → [1, 2, 3, 4]

Stacks and queues

  • A stack (last in, first out) uses push and pop: like a pile of plates.
  • A queue (first in, first out) uses push and shift: like a line at a shop.
script.js
JS
const undoStack = [];
undoStack.push("type A");
undoStack.push("type B");
console.log(undoStack.pop()); // → type B  (the last action is undone first)

A to-do example

index.html
HTML
<input id="task" placeholder="New task">
<button id="add">Add</button>
<button id="removeLast">Remove last</button>
<ul id="list"></ul>
<script>
  const tasks = [];
  const list = document.querySelector("#list");

  function render() {
    list.innerHTML = "";
    for (const task of tasks) {
      const li = document.createElement("li");
      li.textContent = task;
      list.append(li);
    }
  }

  document.querySelector("#add").addEventListener("click", () => {
    const input = document.querySelector("#task");
    if (input.value.trim()) tasks.push(input.value.trim());
    input.value = "";
    render();
  });
  document.querySelector("#removeLast").addEventListener("click", () => {
    tasks.pop();
    render();
  });
</script>

Performance note

shift() and unshift() have to move every other item, so they are slower on very large arrays than push() and pop(). For everyday lists this does not matter.

info
Need a new array instead?
If you want to keep the original untouched, use spread or slice: Spread Syntax for Arrays.