The syntax for this method is fairly straightforward. By definition, the pop method removes the last element in an array and then returns it:
let frozen = [ "Anna", "Elsa", "Olaf", "Kristoff", "Sven" ]; let popped = frozen.pop();
If you were to type this code into the web browser console (*see side note below if you don’t know how to do that), and
console.log (frozen) and
console.log (popped), what would happen?
Frozen would come back as an array with one less element and popped would be the element that was removed from the array:
Chrome/Firefox: In Chrome, right click on this page, select ‘Inspect’. You’ll see the Chrome Developer Tools pop open. At the top there should be a set of navigable tabs. Firefox is similar, but you will select ‘Inspect Element’. Click on Console and your workspace will be there.
You should now be able to type in the information in the example above (or come up with your own example!). Once both frozen and popped variables have been created, console.log both to see the effects the code has on the elements.
The pop method changes the length of the array. You can use it for as long as the length of the array exists. When there is an empty array, the method can still be performed (as in it won’t throw an error or anything), but the popped element will return ‘undefined’.
The pop array method opens up opportunities to use it in logic where we need to remove the last item from an array and then do something with it. This is the opposite of the push method, which adds something to the end of the array and is comparable to the shift method, which removes an element from the front of the array and returns that element.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.