🔜

unshift()

🎉
💨
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];
2
3// Add 1 to the beginning
4numbers.unshift(1);
5
6console.log(numbers); // [1, 2, 3, 4]
7
8// unshift() returns the new length
9const length = numbers.unshift(0);
10console.log(length); // 5
11console.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 unshift
2[2, 3, 4]
3 [0][1][2]
4
5// After unshift(1)
6[1, 2, 3, 4]
7 [0][1][2][3]
8
9// "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