shift and unshift
- Node.js course
- Beginner
- Lesson 56/116
- 5 min
Learn to add/remove at the start with .shift and .unshift.
Prepending with unshift
To add an element at the start of an array you use .unshift(x). arr.unshift(0) places 0 at the start of arr and returns the new length. Existing elements shift one position to the right.
For example after const nums = [2, 3]; nums.unshift(1);, nums becomes [1, 2, 3]. unshift is the start-side counterpart of push. Several values can be added: arr.unshift(-1, 0) prepends both. unshift also modifies the array in place.
Removing from the start with shift
To remove the first element of an array you use .shift(). It returns the removed element and the remaining elements shift one position left. In const nums = [1, 2, 3]; const first = nums.shift();, first becomes 1 and nums is left as [2, 3].
Calling shift on an empty array returns undefined. shift and unshift together give FIFO (first in first out) queue behavior. If you append with push and remove with shift you get a queue. shift also modifies the array in place.
Practice Prepend with unshift and print
The nums variable is set to [2, 3]. Prepend 1 with nums.unshift(1); then print nums[0] with console.log. The output on a single line must be 1.
Starter code
const nums = [2, 3];
// Prepend 1 to nums; print the first elementSample solution
const nums = [2, 3];
nums.unshift(1);
console.log(nums[0]);Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of const a = [2, 3]; a.unshift(1);?
const a = [2, 3];
a.unshift(1);- a = [2, 3, 1]
- a = [1]
- a = [2, 3]
- a = [1, 2, 3] Correct answer
Explanation: unshift prepends 1; a becomes [1, 2, 3].
2 Match each method to its job
| Term | Meaning |
|---|---|
unshift |
Prepends at start |
shift |
Removes from start |
push |
Appends at end |
pop |
Removes from end |
3 Write the shift call
const nums = [1, 2, 3];
const first = nums____();
const nums = [1, 2, 3];
const first = nums.shift();
Explanation: .shift removes the first element.