Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shift() unshift() mnemonics? [closed]

Tags:

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()

like image 293
exebook Avatar asked Oct 01 '13 04:10

exebook


People also ask

What does shift and Unshift do in JavaScript?

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.

What is the Unshift () method?

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

What is the difference between the array Unshift () and the array shift () elements?

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.


2 Answers

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

like image 152
Chokchai Avatar answered Sep 28 '22 17:09

Chokchai


Just think of your keyboard:

Shift gets a capital version of the first key you press.

.shift() gets the first item off the array.

like image 38
quietmint Avatar answered Sep 28 '22 16:09

quietmint