Sunday 2 September 2018

JavaScript: pop: Remove last element from array

By using pop method, you can remove last element from array.

Syntax
arrayName.pop();

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        var array = [2, "Hello", 123.5, true];

        function printArray(arr) {
            document.write("<br />Elements in Array are : ");
            for (var i = 0; i < arr.length; i++) {
                document.write(arr[i] + " ");
            }
            document.write("<br />");
        }

        printArray(array);

        document.write("<br />Poping element");
        array.pop();
        printArray(array);

        document.write("<br />Poping element");
        array.pop();
        printArray(array);

        document.write("<br />Poping element");
        array.pop();
        printArray(array);

        document.write("<br />Poping element");
        array.pop();
        printArray(array);
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

Elements in Array are : 2 Hello 123.5 true

Poping element
Elements in Array are : 2 Hello 123.5

Poping element
Elements in Array are : 2 Hello

Poping element
Elements in Array are : 2

Poping element
Elements in Array are :




Previous                                                 Next                                                 Home

No comments:

Post a Comment