Adding and Removing Elements

An array in JavaScript can grow and shrink. Four methods add or remove elements at the two ends. At the end of the array, you use push and pop:

const guests = ["Alice"];
guests.push("Bob");
console.log(guests);

const last = guests.pop();
console.log(last);
console.log(guests);

Output:

[ 'Alice', 'Bob' ]
Bob
[ 'Alice' ]

push adds an element at the end. pop removes the last element and also returns it, so you can store it in a variable and use it.

A very common pattern starts with an empty array and pushes into it inside a loop:

const squares = [];
for (let n = 1; n <= 4; n++) {
  squares.push(n * n);
}
console.log(squares);

Output:

[ 1, 4, 9, 16 ]

At the front of the array, you use unshift and shift. unshift adds an element at index 0, and every other element moves one place to the right. shift removes the first element and returns it:

const queue = ["Bob", "Carol"];
queue.unshift("Alice");
console.log(queue);

const next = queue.shift();
console.log(next);
console.log(queue);

Output:

[ 'Alice', 'Bob', 'Carol' ]
Alice
[ 'Bob', 'Carol' ]

These pairs match two common ways of handling a list of tasks. A stack takes the newest item first, like the undo history in an editor. For a stack, use push to add and pop to take. A queue takes the oldest item first, like people waiting in a line. For a queue, use push to add and shift to take.

To add or remove elements in the middle of an array, there is a method called splice. You will not need it in this course, so look it up when you do.

All of these methods change the array itself. Changing an array in place like this is called mutating it. Often that is exactly what you want, because a guest list really does change. The next lesson shows tools that build a new array and leave the original alone.

In the exercise, push three names onto a list, add "VIP" at the front, then pop the last name and print it.