Adding and Removing Items
Grow and shrink an array as things change, adding and removing items at the end with push and pop, at the front with unshift and shift, and in the middle with splice.
Apprentice · JavaScript · Updated
After this lesson you can
- Add and remove items at either end of an array with push, pop, unshift and shift
- Remove, insert or replace items in the middle of an array with splice
Key takeaways
pushadds an item to the end andpoptakes the last one off.unshiftandshiftdo the same at the front.popandshiftgive back the item they removed, so you can keep it in a variable.- Adding or removing at the front moves every other item along, so their indexes change.
splice(start, howMany)removes items from the middle, and the values after those two numbers are put in their place.- A
constarray can still gain and lose items.constonly stops the name from pointing to a different array.
A list that never changes isn't much use. On the road trip, someone in the back seat begs for one more song, a song everyone is tired of gets dropped, and the driver wants a slow one moved up before the long night stretch. The same thing happens in every app with a list: an item goes into a shopping cart, a message is deleted, a new order joins the line at a coffee shop. This lesson is how your code keeps up.
Adding to the end: push
The most common change is adding something to the end of the list, the way a new song goes to the bottom of a playlist. The array method for it is push. A method is an action an array knows how to do: write the array's name, a dot, the method's name and parentheses, with whatever it needs inside.
const playlist = ['Highway Sunrise', 'Desert Radio'];
playlist.push('Windows Down');
console.log(playlist);
const newLength = playlist.push('Mile Marker 9', 'Last Exit Lights');
console.log(playlist);
console.log(newLength);
[ 'Highway Sunrise', 'Desert Radio', 'Windows Down' ]
[
'Highway Sunrise',
'Desert Radio',
'Windows Down',
'Mile Marker 9',
'Last Exit Lights'
]
5
push can add several items at once, in the order you give them. It gives back the array's new length, which you can keep or ignore. When an array gets long, Node prints one item per line; it's the same array.
Taking off the end: pop
pop removes the last item and gives it back to you, like taking the top plate off a stack:
const playlist = ['Highway Sunrise', 'Desert Radio', 'Windows Down'];
const skipped = playlist.pop();
console.log(skipped);
console.log(playlist);
Windows Down
[ 'Highway Sunrise', 'Desert Radio' ]
pop needs nothing in its parentheses: it always takes the last item. On an empty array there's nothing to take, and it gives back undefined.
The front of the list: unshift and shift
The front of the array has its own pair. unshift adds an item at the start, and shift removes the first one and gives it back. Think of a line at a coffee shop: shift serves the person at the front, and everyone behind moves up one place.
const playlist = ['Highway Sunrise', 'Desert Radio', 'Windows Down'];
playlist.unshift('Sunset Detour');
console.log(playlist[0], playlist[1]);
const nowPlaying = playlist.shift();
console.log(nowPlaying);
console.log(playlist[0]);
Sunset Detour Highway Sunrise
Sunset Detour
Highway Sunrise
Watch what happens to the indexes. After unshift, Highway Sunrise moved from index 0 to index 1, and every other song moved along with it. After shift, they all moved back. If your code kept a song's index from before the change, that number now points at a different song.
To keep them straight: push and pop work at the end; unshift and shift work at the start.
Try it. Make a file named queue.js with an array of three drink orders for a coffee shop. A new order arrives (push), the first order is served (shift, and print who got served), then print the orders still waiting. Run it with node queue.js.
The middle of the list: splice
To change the middle of an array, use splice (it rhymes with "slice", and means joining two ends together, the way you splice a rope). It takes the index to start at, then how many items to remove, then any items to put in their place:
array.splice(start, howManyToRemove, itemToAdd, anotherItemToAdd);
Only the first number is needed, but you'll almost always give two. Here are the three jobs it does:
const playlist = ['Highway Sunrise', 'Gas Station Coffee', 'Desert Radio', 'Windows Down'];
const removed = playlist.splice(1, 1);
console.log(removed);
console.log(playlist);
playlist.splice(2, 0, 'Mile Marker 9');
console.log(playlist);
playlist.splice(0, 1, 'Sunset Detour');
console.log(playlist);
[ 'Gas Station Coffee' ]
[ 'Highway Sunrise', 'Desert Radio', 'Windows Down' ]
[ 'Highway Sunrise', 'Desert Radio', 'Mile Marker 9', 'Windows Down' ]
[ 'Sunset Detour', 'Desert Radio', 'Mile Marker 9', 'Windows Down' ]
- Remove:
splice(1, 1)starts at index 1 and removes one song. It gives back the removed songs as an array of their own. - Insert:
splice(2, 0, 'Mile Marker 9')starts at index 2, removes nothing (0), and puts the new song there. The songs after it move along. - Replace:
splice(0, 1, 'Sunset Detour')removes one song at index 0 and puts the new one in its place.
Be careful with the first number: splice(2) with no second number removes everything from index 2 to the end.
Why a const array can still change
In Module 1 you met const, read "constant": a variable that can't be given a new value. So how did every playlist above change? Think of the variable's name as a label stuck on a box. const glues the label to that one box for good. You can still put songs into the box and take them out; what you can't do is move the label to a different box.
const playlist = ['Highway Sunrise'];
playlist.push('Desert Radio');
playlist[0] = 'Sunset Detour';
console.log(playlist);
playlist = ['Windows Down'];
[ 'Sunset Detour', 'Desert Radio' ]
The first three lines run: they change what's in the array. The last line tries to point the name at a brand-new array, and Node stops with TypeError: Assignment to constant variable. That's why most JavaScript code declares arrays with const: the list can change as much as it needs to, and the name can never end up pointing at the wrong list by accident.
Try it. In queue.js, add the line orders = []; at the end and run it. Read the error, then delete the line.
Check yourself
2 questions to try on the lesson page.
So what
Real lists change all the time. With push, pop, unshift, shift and splice, your code can keep a playlist, a cart or a line of orders up to date, whatever people do.