DEV Community

Kenneth Lum
Kenneth Lum

Posted on

How to remember JavaScript's shift() and unshift() ?

Sometimes it is easy to do the exact opposite when we mean to add some value to the front of the array. Is it shift() or unshift()? If it is a whiteboard interview or online interview, it may help if we can remember which is which, instead of looking it up online.

To add the value to the front of the array, it is unshift(). Maybe the "un" part of "unshift" makes us think it is unloading something or undoing something. But in fact, it is the "opposite". We can remember unshift(), opposite to what it sounds like, adds the value to the front, and shift() takes the value out of the array.

And just like other traditional Array methods before ES6, it is "in-place" modification (only slice() and concat() create new arrays, if we don't consider the map() and filter(), which are the newer array methods.)

> arr = [2,4,6]
[ 2, 4, 6 ]

> arr.unshift(1,3,5)    // the length is returned
6

> arr
[ 1, 3, 5, 2, 4, 6 ]

> arr.shift()
1

> arr.shift()
3

> arr.shift(2)          // the 2 has no use. Only one value is shifted out
5

> arr.shift()
2

> arr
[ 4, 6 ]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

Never tried this: > arr.shift(2) .
I am glad I read your post :P