JavaScript Interview Question #39
What is the difference between push(), pop(), shift(), and unshift()?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
push adds one or more elements to the end of an array, while pop removes and returns the last element. unshift adds elements to the beginning, while shift removes and returns the first element.
Detailed Explanation
push adds one or more elements to the end of an array, while pop removes and returns the last element. unshift adds elements to the beginning, while shift removes and returns the first element.
All four methods mutate the original array. Operations at the beginning may require reindexing elements and can be less efficient for large arrays than operations at the end.
Code Example
const items = ["B", "C"];
items.push("D"); // ["B", "C", "D"]
items.unshift("A"); // ["A", "B", "C", "D"]
const first = items.shift(); // "A"
const last = items.pop(); // "D"
console.log(items); // ["B", "C"]