Do you know about javascript array push() and pop() methods?

Hey, what’s up, guys.

Javascript array has some interesting methods. In this post, I will be talking about javascript push and pop methods that are used to add and remove elements from a javascript array. So without further ado let’s see what javascript push() and pop() methods are.

What is the push() method in javascript?

You use the push() method to add new elements to an array. The new element goes at the end of the array. After adding the element push() method returns the length of the new array.

Example-

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript push() Method</h1> 

<p id="id1"></p>
<p id="id2"></p>

<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];

//Adding element to the array using push().
//This method returns length of the array after adding the element.
document.getElementById("id1").innerHTML = cars.push("Bentley");

//Displaying elements after adding a new element.
document.getElementById("id2").innerHTML = cars;
</script>

</body>
</html>

Output :

JavaScript push() Method

5

Porsche,BMW,Audi,Jaguar,Bentley

In this example, I am calling the push() method and passing ‘Bentley’ as a parameter to the push() method. After adding ‘Bentley‘ to the cars array the push() method has returned the length of the new cars array that is 5.

What is pop() method?

You use the pop() method to remove the last element from an array. The return value of the pop() method is the element that was “popped out”.

Example –

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript pop() Method</h1> 

<p id="id1"></p>
<p id="id2"></p>

<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];

//Removing element from cars array using pop().
//This method returns the element that was popped out.
document.getElementById("id1").innerHTML = cars.pop()

//Displaying cars array elements after performing pop() operation.
document.getElementById("id2").innerHTML = cars;
</script>

</body>
</html>

Output :

JavaScript pop() Method

Jaguar

Porsche,BMW,Audi

In this example, I am calling pop() method on cars array. This method will remove the last element ‘Jaguar’ from the cars array and return the removed item ‘Jaguar’ (see the output). After removing an element I am displaying the elements of the cars array.

So that’s all about javascript push() and pop() methods.

Have any question in mind?

Comment below.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: