When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
Popping
The pop()
method removes the last element from an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes "Mango" from fruits
fruits.pop(); // Removes "Mango" from fruits
The pop()
method returns the value that was "popped out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop(); // x = "Mango"
let x = fruits.pop(); // x = "Mango"
Pushing
The push()
method adds a new element to an array (at the end):
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds "Kiwi" to fruits
fruits.push("Kiwi"); // Adds "Kiwi" to fruits
The push()
method returns the new array length:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.push("Kiwi"); // x = 5
let x = fruits.push("Kiwi"); // x = 5
Practice Excercise Practice now