Push, Pop, Pez & Understanding JavaScript Functions
I had a bit of difficulty remembering the exact way push and pop functions in JavaScript work until I thought of the PEZ dispenser.
When you have an array that you create like this:
var bob = [1,47] ;
and you do this:
bob.push(9,12)
now your new array is [1,47,9,12]
In other words, push adds the elements at the end of the array.
It always seemed to me that it should be adding it to the beginning until I thought of the PEZ dispenser. If your array was a PEZ dispenser and you added something to the PEZ-array you would add it to the top, wouldn’t you? Of course you would!
When you push an element into an array, the length of the array increases by however many elements you pushed. Similarly, if you had 7 candies in your dispenser and added two more, of course your stack of candy is now equal to 9 pieces.
Similarly, the pop function, returns the value of the top element in the array and removes that element from the array. It also reduces the length of the array.
So, after I had pushed the new elements to my array named bob, if I did this
bob.pop()
it would return the value of 12 and leave bob as this array — > [1,47,9]
and bob.length = 3
If you think about it, that is exactly like what happens when you pop a candy in your mouth from the PEZ dispenser. You get whichever one is on top, that candy is no longer in the dispenser and your total number of pieces of candy is one less.
If you want to add elements to the FRONT of the array, use the unshift function, like so
bob.unshift(42)
and if you want to remove an element from the front of the array, use the shift function, like this
bob.shift()
Think of it like everyone at a movie theater shifting over one seat to be closer to the aisle.
Sorry I do not have a candy analogy for the shift and unshift.
Thanks to Debbie for putting the Hello Kitty PEZ dispenser on wikimedia.
The PEZ store photo was taken by the rocket scientist. There is actually a store in Universal Citywalk Hollywood where you can buy hundreds of different types of PEZ dispensers if you are into that sort of thing. There’s also a PEZ dispenser conference in California every year, just in case you were wondering where besides this blog you could go to expand your PEZ-related knowledge.
Nice comparison used to explain a stack data structure.
I was taught to think of stacking dishes after drying them. You stack dishes with push and pop removes the top one. You can’t remove any other dish than the top dish or you will crash and break all your dishes. I always liked that analogy because I don’t like breaking dishes. And I always thought it was fun to see how high I could stack dishes. 🙂
The stack (push and pop) is LIFO (last-in, first-out).
It’s also the mechanism for how I select my clothes every morning.
And the shift function is how your mother TOLD you to select your clothes every morning a.k.a. the FIFO method