The shift() method removes the first element from an array and returns that element.
✅ Implementation
Array.prototype.customShift = function () { if (this.length === 0) return undefined; // Return undefined if the array is empty const firstElement = this[0]; // Store the first element // Shift all elements to the left for (let i = 1; i < this.length; i++) { this[i - 1] = this[i]; } this.length -= 1; // Reduce the length of the array return firstElement; // Return the removed element }; // Example usage: const array = [1, 2, 3]; const firstElement = array.customShift(); console.log(firstElement); // Output: 1 console.log(array); // Output: [2, 3] console.log([].customShift()); // Output: undefined (empty array case)
How It Works
- Handles an empty array
- If
this.length === 0, it returnsundefined, just likeshift().
- If
- Stores the first element
- Saves
this[0]before modifying the array.
- Saves
- Shifts elements to the left
- Iterates through the array and shifts elements to the left (
this[i - 1] = this[i]).
- Iterates through the array and shifts elements to the left (
- Reduces the array length
this.length -= 1;effectively removes the last duplicate.
- Returns the removed element
- Mimics
shift()behavior by returning the removed item.
- Mimics
Edge Cases Handled
✔ Works on normal arrays
✔ Works on empty arrays ([].customShift() → undefined)
✔ Modifies the original array in place
✔ Returns the first element as expected
This implementation is simple, efficient, and follows Array.prototype.shift exactly.
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `[].customShift()` return?
Q2What is the time complexity of the `shift()` operation?
Q3How does the shift polyfill work internally?