Push VS Unshift

On mdn web docs I read this:

The unshift() method of Array instances adds the specified elements to the beginning of an array and returns the new length of the array.

And:

The push() method of Array instances adds the specified elements to the end of an array and returns the new length of the array.

I was wondering what are the advantages of using unshift vs push when adding elements to an array.
Thank you

It doesn’t offering any advantage. They don’t do the same thing. One pushes to the right side (the end of the array) and the other unshifts to the left side (the beginning) of the array. We only need to decide which works for our given situation.

When we think of push (and pop) we can equate that to a stack, which can also be said of unshift and shift. A stack works in a ‘last on/first off’ manner. Now if we consider a queue, it’s first on, first off so we combine push with shift, or unshift with pop to effect that insertion/removal order.

None of this is meant to make any sense, just now, but it will in due course of time. For now, just think in terms of which end of the array you wish to insert at: prepend (left) or append (right).

 > arr = [3, 4, 5]
<- (3) [3, 4, 5]
 > arr.unshift(2)
<- 4    //  new length of the array
 > arr
<- (4) [2, 3, 4, 5]
 > arr.push(6)
<- 5    //  new length of the array
 > arr
<- (5) [2, 3, 4, 5, 6]
 > arr.shift()
<- 2    //  value taken out of the array
 > arr.pop()
<- 6    //  value taken out of the array
 > 
1 Like