How to Remove Last Element from an Array in Javascript?

Sep 13, 2022 . Admin



Hello dev,

This article is focused on how to remove last element from an array in javascript. I would like to share with you how to remove last array element in javascript. I explained simply step by step remove the last element from an array in javascript. In this article, we will implement a remove array last element using javascript.

In this tutorial, I am going to explain to you to remove the last element of the array in javascript. The standard way to remove the last element from an array is with the pop() method. This method works by modifying the original array.

In the second example, we have another method to remove the array's last element. The splice() method is often used to in-place remove existing elements from the array or add new elements to it. The following example demonstrates the usage of the splice() to remove the last element from the array.

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Last Element from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Last Element from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var arr1 = ["Red","Yellow","Green","White"];
            var last = arr1.pop();

            //Give output to console...
            console.log(arr1);

            //Removed element...
            console.log(last);
        </script>
    </body>
</html>
Output:
['Red', 'Yellow', 'Green']
White
Example: 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Last Element from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Last Element from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            var arr1 = ["Red","Yellow","Green","White"];
            var last = arr1.splice(arr1.length -1);

            //Give output to console...
            console.log(arr1);

            //Removed element...
            console.log(last);
        </script>
    </body>
</html>
Output:
['Red', 'Yellow', 'Green']
['White']
I hope it will help you...
#Javascript