Four methods add or remove items at the ends of an array. All of them change the original array (they mutate it).
| Method | End | Action | Returns |
|---|---|---|---|
push(x) | end | add | the new length |
pop() | end | remove | the removed item |
unshift(x) | start | add | the new length |
shift() | start | remove | the removed item |
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
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
pushandpop: like a pile of plates. - A queue (first in, first out) uses
pushandshift: like a line at a shop.
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
<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.
Need a new array instead?
slice: Spread Syntax for Arrays.