JavaScript pop method - Syntax & Examples
In this quick tutorial, we will be looking at the
pop()
method in JavaScript. We will go through its syntax and workings with examples.Table of Contents - JavaScript pop()
- What is JavaScript pop?
- Syntax and parameters
- Making use of the JavaScript pop() method
- Using call() on array like objects
- Closing thoughts
- Other Related Concepts
What is JavaScript pop?
Thepop()
method removes (or pops) the last element in a given array. The method makes a change to the original array itself by this removal action. Finally, the method returns the removed element to us.This method is intentionally generic. It is so as to ensure that this method can be applied or called to objects resembling arrays.
If you call
pop()
of an empty array, it returns undefined.
The shift() function has a similar purpose like
pop()
, except that it works on the first element in an array.Syntax and parameters
Here is the syntax for the method:Syntax:
array.pop()
For the JavaScript pop()
method, we don’t have any parameters to consider. But what is the return value we can expect? Return value:The returned value is of variable type. It can be a string, a number, an array or just about any type allowed in an array.
Making use of the JavaScript pop() method
Let’s take a look at the following code. The arraymyFram
contains 4 elements. The method removes the last element from the array and returns the last element.Input:
var myFram = ['angular', 'react', 'vanilla', 'node'];
var whatsPoppin = myFram.pop();
console.log(myFram);
console.log(whatsPoppin);
Output:
[ 'angular', 'react', 'vanilla' ]
node
In this code snippet here, we can see that we had an array called myFram
with 4 elements. When the pop()
method was applied the last element of the array was removed. The code console.log(myFram)
now returns the updated array. Finally, the last line of code, console.log(whatsPoppin)
returns the popped element.Using call() on array like objects
Thecall()
method is a predefined JavaScript method. With call()
, an object can use a method belonging to another object. Let’s see how this can be used with the pop method.Input:
var myTech = {0:'react native', 1:'flutter', 2:'kotlin', 3:'swift', length: 4};
var whatsPoppin = Array.prototype.pop.call(myTech);
console.log(myTech); //{ '0': 'react native', '1': 'flutter', '2': 'kotlin', length: 3 }
console.log(whatsPoppin); // 'swift'
In the code snippet above, the code creates the myTech
array-like object. The array contains 4 elements and a length parameter. The pop()
method removes the last element of the array and then also decreases the length parameter.Closing thoughts
In this short tutorial we saw what thepop()
method of JavaScript does. We understood the syntax and return value of the method as well.In contrast, the JavaScript
push()
method is used to add items to the end of an array. The syntax and working is exactly the same as the pop()
method, but its intended purpose is different.