I am having hard time remembering what Array.shift()
and Array.unshift()
do.
After few years, I still have too check out reference from time to time when I need to use one of them. Can anyone explain why those names are choosen and how to memorize which one does what?
I have no such problem with Array.push()
and Array.pop()
The shift() method in JavaScript removes an item from the beginning of an array and shifts every other item to the previous index, whereas the unshift() method adds an item to the beginning of an array while shifting every other item to the next index.
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
The shift() function lets you remove an item from the start of an array. The the unshift() function adds one or more items to the start of an array.
As I known.
The shift command is come from the binary bit shift [1]. for Example.
001100 0 < 011000 // when you shift left | Yay!
I think it is quite simple it is just like you push it from behind. So this makes sense for me.
The unshift is the opposite way of shift.
001100 1 > 001100 // they called it unshift 1001100 | Yay!
So that's it, Hope this helps!
[1] http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
Just think of your keyboard:
Shift gets a capital version of the first key you press.
.shift()
gets the first item off the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With