JavaScript Array pop() Tutorial

In this section, we will learn what the pop() method is and how to use it in JavaScript.

JavaScript Arrays pop() Method

The `pop()` method removes and returns the last element of the target array.

This means every time we call the method; the array will lose its size by one.

For example, calling the pop() method on the array [1,2,3,4,5] will return the value 5 and the array itself becomes [1,2,3,4].

Array pop() Syntax:

array.pop()

Array pop() Method Parameters:

This method does not take any argument.

Array pop() Method Return Value:

Again, the last element of the target array will be the returned value of this method.

Example: JavaScript get Last Element of Array

const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"];
const size = arr.length;
for(let i = 0 ; i<size; i++){
  console.log(`The length of the array is: ${arr.length}`);
  console.log(arr.pop());
}

Output:

The length of the array is: 6

Twitter

The length of the array is: 5

Facebook

The length of the array is: 4

Amazon

The length of the array is: 3

Microsoft

The length of the array is: 2

Google

The length of the array is: 1

Tesla

Example: JavaScript empty an array

const obj1 = {
   name: "John", 
   age: 1000,
   toString(){
      return ` ${this.name}, ${this.age} `;
   }
}
const obj2 = {
   name: "Omid",
   age: 29,
   toString(){
      return ` ${this.name}, ${this.age} `;
   }
}
const obj3 = {
   name : "Jack", 
   age :52,
   toString(){
      return `${this.name}, ${this.age}`;
   }
}
const arr = [obj1,obj2,obj3];
while(arr.length != 0){
   console.log(arr.pop().name);
}
console.log("The target array is empty now!");

Output:

Jack

Omid

John

The target array is empty now!
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies