Arrays! And memory tricks for keeping shift and unshift straight

I just spent about an hour studying arrays. I thought I had a good handle on them, and I'm sure at one point I did, but there was PLENTY of material that I needed to re-study as a refresher. Studying the basics as part of my Hack Reactor precoursework has been very humbling, and I'm really happy that they make us do this!

One thing that I often get confused about is shift() and unshift(). Both of these methods do different things to an array and return non-obvious elements. How to keep them straight? I'll get into that in a moment.


The shift() method removes the first element of an array and returns it. It changes the length of the array. If the array has a length of 0, then array.shift() returns undefined .

The unshift() method adds one or more elements to the beginning of an array, and returns the new length of the array. Like shift , it changes the length of the array.

var arr = [1, 2, 3];
console.log(arr.shift()); // 1 
console.log(arr); // [ 2, 3 ]
console.log(arr.unshift(0)); // 3 <- new length of arr
console.log(arr); // [ 0, 2, 3 ]

Memory tricks

Warning: These are silly! But they work for me.

  • Lots of F's: shiFt and unshiFt = the Front of an array.
  • Think of shift like a worker getting off their shift, using a first in [index 0], first out approach. So whoever is at the start of the line [index 0] gets off their shift, and is returned to you. The array actually changes as a result: You have one fewer worker, and all remaining workers are moved up towards the front of the line by one position.
  • Think of the Unshift Family as an annoying family obsessed with how many people they have (like those people who are really into geneology, and keeping in business), so they're going to return the size of their family.
  • Unshift is a fatter word than shift, so of course you're going to end up with a "fatter" array.

I love mnemonic devices (basically attaching a "sticky" mental association to new words so you remember their meanings better - I'm pretty sure that's NOT the scientific definition, btw). I've picked up multiple languages -- from Arabic to Albanian -- using mnemonic devices. The key is not to be embarrassed by the weird turns and graspings that your mind will take in order to attach meaning to a new word or concept. You only need the device while you're learning.

At some point, your reliance on the device falls away and you'll just know that shift() returns the first element of an array, or that "Faleminderit" means "thanks" in Albanian, and you'll evven forget the mnemonic you used to get you there! Brains are awesome like that.