JavaScript - pop() method

revision:


Category : array

The pop() method removes (pops) the last element from an array and returns that element. This method changes the length of the array.

It changes the original array and returns the removed element.

Syntax :

        pop()
    

Parameters: none

Examples:

            const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
            console.log(plants.pop());
            // Expected output: "tomato"
            console.log(plants);
            // Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
            plants.pop();
            console.log(plants);
            // Expected output: Array ["broccoli", "cauliflower", "cabbage"]
        

Practical examples

example: removing the last element of an array.

code:
                    <div>
                        <p id="pop-1"></p>
                        <p id="pop-2"></p>
                        <p id="pop-3"></p>
                    </div>
                    <script>
                        const myFish = ["angel ", "clown ", "mandarin ", "sturgeon "];
                        document.getElementById("pop-1").innerText = "array fish: " + myFish;
                        const popped = myFish.pop();
                        console.log(myFish); // ['angel', 'clown', 'mandarin' ]
                        console.log(popped); // 'sturgeon'
                        document.getElementById("pop-2").innerText = "array popped:" + myFish;
                        document.getElementById("pop-3").innerText = "popped:" + popped;
                    
                

example: remove (pop) the last element.

code:
                    <div>
                        <p id="pop-4"></p>
                        <p id="pop-5"></p>
                    </div>
                    <script>
                        const fruits = ["Banana", "Orange", "Apple", "Mango"];
                        document.getElementById("pop-4").innerHTML = "array : " + fruits;
                        fruits.pop();
                        document.getElementById("pop-5").innerHTML = "array popped : " + fruits;
                    </script>
                

example: pop() method returns the element it removed.

code:
                    <div>
                        <p id="pop-6"></p>
                        <p id="pop-7"></p>
                    </div>
                    <script>
                        const fruits1 = ["Banana", "Orange", "Apple", "Mango"];
                        document.getElementById("pop-6").innerHTML = "array : " + fruits1;
                        let removed = fruits1.pop();
                        document.getElementById("pop-7").innerHTML = "removed fruit : " + removed;
                    </script>