pop() Method in JavaScript
•JavaScript•1 min read

javascriptpop methodarray methods
pop() is a built-in method in JavaScript that removes the last element from an array and returns the removed element.
pop() Method in JavaScript
pop()is a built-in method in JavaScript that removes the last element from anarrayand returns the removed element.- It also modifies the original array, reducing its length by one.
Example:
- let's take an array
pageHistory, with elements like home, about and contact.
let pageHistory = ['home', 'about', 'contact'];To show all pages, use the forEach() method.
let pageHistory = ['home', 'about', 'contact'];
pageHistory.forEach(page => {
document.write(page + "<br>");
});
// Output:
home
about
contactNow, all the pages in the array are displayed as home, about, contact.
If you want the last page, use the pop() method to get the last page:
let pageHistory = ['home', 'about', 'contact'];
let lastPage = pageHistory.pop();
document.write("Last Page: " + lastPage);
pageHistory.forEach(page => {
document.write(page + "<br>");
});
// Output-1:
Last Page: contact
// Output-2:
home
aboutThe last page contact is shown, and in the pageHistory array, there are only two pages left (home, about).
If you use the pop() method again, it will show the about page:
let pageHistory = ['home', 'about'];
let lastPage = pageHistory.pop();
lastPage = pageHistory.pop();
document.write("Last Page: " + lastPage);
pageHistory.forEach(page => {
document.write(page + "<br>");
});
// Output-1:
Last Page: about
// Output-2:
homeNow, in the pageHistory array, there is only one page left home.
- Like this, we can remove and get all pages from the array.



