DEV Community

Kenneth Lum
Kenneth Lum

Posted on

2 2

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

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