Mnemonic for array.shift() vs array.unshift() in JavaScript

Published on in JavaScript and Mnemonics

Last updated on

shift() removes the first array item, and unshift() prepends items to the array. But how to remember which is which?

First, you need to remember pop() vs push(). If you don't, try these mnemonics:

  • pop() removes the last array item by popping it like a bottle cap.
  • push() appends items to the array by... eh, pushing stuff to it?

I think they are quite intuitive.

All right, now the mnemonic for shift() vs unshift() (and incidentally also for pop() vs push()):

The method with the shorter name removes an item.

So, pop() and push():

  • pop() has a shorter name than push().
  • pop() removes the last array item.
  • push() appends items to the array.

Similarly, shift() vs unshift():

  • shift() has a shorter name than unshift().
  • shift() removes the first array item.
  • unshift() prepends items to the array.