Adding and removing
In the previous lesson we changed the elements of an array, but their number stayed the same. Yet many lists grow and shrink. Take a shopping list: a new item is added at the end, and the last item, once bought, is crossed out.
An array has methods for this kind of work. The push method adds an element to the end of an array, and pop removes the last element and returns it:
const cart = ["milk", "bread"];
console.log(cart.push("eggs")); // 3
console.log(cart.join(" ")); // milk bread eggs
console.log(cart.pop()); // eggs
console.log(cart.join(" ")); // milk breadLet's go through it line by line:
cartholds two items:"milk"and"bread".cart.push("eggs")adds"eggs"to the end and prints3, the new length.cart.join(" ")shows that there are now three items.cart.pop()removes the last item and prints it:eggs.- The last line prints
milk bread: the array is back to how it started.
The shopping list analogy is incomplete. On a paper list a crossed-out item stays visible, while pop removes the element from the array completely and hands it to you.
The end of an array
push
A push call returns the new length of the array, not the added element. That is why the second line of the example prints 3. Interviewers like to ask about this: the answer "push returns the element" is wrong.
One push call can also take several elements: cart.push("tea", "jam") adds both in order.
pop
pop takes nothing. It removes the last element and returns it, so you can save the removed value in a variable or print it right away.
Building a new array
Most often, push builds a new array in a loop. The array starts as [], and the matching elements are added to it one by one:
const nums = [3, -1, 4, -5];
const positive = [];
for (const n of nums) {
if (n > 0) {
positive.push(n);
}
}
console.log(positive.join(" ")); // 3 4
console.log(nums.length); // 4The loop goes through nums and puts only the positive numbers into positive. The original array nums does not change: it still holds four elements.
The start of an array
Two similar methods with the same rules work on the start of an array:
unshiftadds elements to the start and returns the new length;shiftremoves the first element and returns it.
The indexes of the other elements move by one. One rule covers all four methods: the adding ones return the new length, and the removing ones return the removed element.
const queue = ["Ann", "Bob"];
console.log(queue.unshift("Eve")); // 3
console.log(queue.join(" ")); // Eve Ann Bob
console.log(queue.shift()); // Eve
console.log(queue.shift(), queue.length); // Ann 1An empty array has nothing to remove. Then pop and shift return undefined, and the array stays empty.
Changing in place
All four methods mutate the array in place: no new array is created, and the one the method was called on changes. That is why they can be called on an array in a constant: const does not protect the array's contents.
Strings never work this way. A string is immutable, and its methods, such as toUpperCase, return a new string. The array methods push, pop, shift and unshift, on the contrary, change the array itself.
Assigning a new array to a constant is still not allowed. The line cart = [] stops the program with TypeError: Assignment to constant variable., like any assignment to a constant.
Common mistake
The result of push is put back into the array variable:
let names = ["Ann"];
names = names.push("Bob"); // ✗
names.push("Eve");TypeError: names.push is not a functionThe error comes on the third line, but its cause is in the second. push returned the length 2, so names now holds a number, and a number has no push method.
The array has already changed in place, so the result of push does not need to be assigned: write names.push("Bob");.
Key points
pushandunshiftadd elements to the end and to the start and return the new length.popandshiftremove the last and the first element and return it, orundefinedfor an empty array.- All four methods change the array in place, even when it is in a constant.
- A new array is built like this: start with
[]and callpushin a loop.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.