Problem Statement
Explain push, pop, shift, and unshift methods. What is the difference between them?
Explanation
These are the four basic methods for adding and removing elements from arrays.
Push adds one or more elements to the end of an array. It modifies the original array and returns the new length. Use push when building up an array or adding items to the end.
Pop removes the last element from an array. It modifies the original array and returns the removed element. Use pop when you need to remove from the end, like implementing a stack.
Shift removes the first element from an array. It modifies the original array, shifts all other elements down by one index, and returns the removed element. Use shift when you need to remove from the beginning, but note it is slower than pop.
Unshift adds one or more elements to the beginning of an array. It modifies the original array, shifts all existing elements up by one index, and returns the new length. Use unshift to add to the beginning, but note it is slower than push.
Performance note:
Push and pop are fast operations. Shift and unshift are slower because they require reindexing all elements.
For queue operations, consider using push and shift, or better yet, a proper queue data structure for large datasets.
Code Solution
SolutionRead Only
const arr = [1, 2, 3]; // push - add to end const newLength = arr.push(4, 5); console.log(arr); // [1, 2, 3, 4, 5] console.log(newLength); // 5 // pop - remove from end const last = arr.pop(); console.log(arr); // [1, 2, 3, 4] console.log(last); // 5 // unshift - add to beginning const length2 = arr.unshift(0, -1); console.log(arr); // [-1, 0, 1, 2, 3, 4] console.log(length2); // 6 // shift - remove from beginning const first = arr.shift(); console.log(arr); // [0, 1, 2, 3, 4] console.log(first); // -1 // Stack (LIFO - Last In First Out) const stack = []; stack.push(1); // Add to top stack.push(2); stack.push(3); console.log(stack.pop()); // 3 (remove from top) // Queue (FIFO - First In First Out) const queue = []; queue.push(1); // Add to end queue.push(2); queue.push(3); console.log(queue.shift()); // 1 (remove from beginning) // All modify original array const original = [1, 2, 3]; original.push(4); console.log(original); // [1, 2, 3, 4] (changed)
