I help run a bi-weekly algorithm coding guild at work where we solve many programming problems together. It’s a very fun and rewarding experience and I get exposed to many different programming languages. Sometimes, when I “shift gears” between languages, I mix up the prototype methods in javascript.
The one I recently flubbed was shift()
and unshift()
, which seems silly but when you’re moving fast its an honest mistake to make!
Let’s review their MDN entries
Array.prototype.shift()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift#description
Array.prototype.unshift()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift#description
How I always remember the difference:
If we literally break up the words into letters (similar to split()
lol) you might notice something:
["u","n","s","h","i","f","t"]
vs["s","h","i","f","t"]
The way I see it, unshift is “updating” our array above, “shift” with two additional characters in the front (“u” and “n”). In my mind I also remember this by matching up the “u” of update and “u” of unshift. Shift on the other hand complements this as its missing the “u. ” In fact this is even how unshift()
works! It prepends characters to the front of the array.
Hope this little trick helps you! Remember we update (think “u” ) with unshift… with two characters in the front of the word shift > unshift.