Sometimes it is easy to do the exact opposite when we mean to add some value to the front of the array. Is it
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
concat() create new arrays, if we don't consider the
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 ]
Claim your page on DEV before someone else does
Level up every day