🎉
💨
Adding a new engine to the front of our train!
The unshift() Method
The unshift() method adds items to the beginning of an array.
It's like attaching a new engine at the front - all the other cars have to move back to make room!
💡
💨
How unshift() Works
1const numbers = [2, 3, 4];23// Add 1 to the beginning4numbers.unshift(1);56console.log(numbers); // [1, 2, 3, 4]78// unshift() returns the new length9const length = numbers.unshift(0);10console.log(length); // 511console.log(numbers); // [0, 1, 2, 3, 4]
🤔
💨
All Indices Shift Right!
When you unshift(), all existing items move to the right. Their index numbers all increase!
1// Before unshift2[2, 3, 4]3 [0][1][2]45// After unshift(1)6[1, 2, 3, 4]7 [0][1][2][3]89// "2" moved from index 0 to index 1!
🎮
Try It Yourself!
Add items to the front of the array. Watch everything shift to make room!
[
2
[0]3
[1]4
[2]]
length: 3