r/javascript • u/freebit • Mar 24 '18
Can't keep Array.shift vs Array.unshift straight? (NSFW) NSFW
Here is a helpful, although gross mnemonic to help keep the two straight in your head. Drop the "f".
So, Array.shit() drops a load (element) from the beginning of an array and Array.unshit() will do the opposite.
69
Upvotes
8
u/sh0rtwave Mar 24 '18 edited Mar 25 '18
Some day, we'll get it right and realize we just need clear semantics for what these damned things actually do.
Teaching array.pop/push/slice/shift/unshift is one of the toughest things to do, IMHO.
Everbody gets pop and push, instantly. They make sense. We all know about popping something off the top of a stack of dishes and pushing something else back on top of it.
So does "slice". (Who doesn't understand slicing a pie?). We're just taking SOME of the dishes out of the stack, and maybe sticking new ones in. Makes sense. Lift the top part of the stack you're leaving, stick something new in, take something out, set them back down. Easy-peasy.
In fact, almost all the other functions are simple to understand, because they relate to physical things we can understand.
So that stack of plates...how does unshift work? So really, what you're doing is lifting the entire stack, and then...un-shifting(carefully scooting) the bottom plate with your foot into place so you can put that big stack back down on top of it.
Shift? Lift that whole stack of plates with both hands, and kick that bottom plate out with vigor.
I find, when explaining things to people about computing, it's best if you can grab an idea of the physical act you're doing, it aids with understanding in a whole other way than just being a memory tool.
Edit: I should mention...it took me a year or so of teaching(adults) to come up with that. Some of my students (mostly adult) had serious problems grasping even things like variables. Seriously, I had to use cups + water + food coloring to simulate the idea that a variable can NOT hold two values at a time. (That came in useful in many situations, e.g. AoCP Q#1.)
Edit again: Don't even get me started about trying to explain bitmasks.
Edit again again: Explained it backwards like an idiot.