JavaScript Glossary - Lesson #12

JavaScript Array .pop() Method

This method takes out the last element from an array and returns it. The pop method mutates the array during this process reducing its length.

js
['me', 'him', 'you'].pop()
js
// List of names
const students = ['william', 'john', 'chris', 'mike']

// Remove the last name
const newStudents = students.pop()

// Output the removed name
console.log(newStudents) // mike

This method when called:

  • Removes the element at the last index of the array.
  • Mutates the parent array reducing the length.
  • Returns the last element.
js
array.pop()

The pop() method will return the element removed from the array. If the array is empty, it returns undefined.

js
const names = ['Johnny', 'Pete', 'Sammy']
console.log(names.pop());
// output: 'Sammy'

The pop method is mostly used to remove the last element of an array and output both the parent array and the value removed.

Remove item in a list and return list:

js
// List of items
let items = ['Cedar', 'Fruits', 'Table'];

// Remove last item in list
let newItems = items.pop();

// Output modified list
console.log(items); // ["Cedar","Fruits"]

// Output removed item
console.log(newItems) // Table

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)