When you have an array that you create like this:
var bob = [1,47] ;
and you do this:
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
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
and if you want to remove an element from the front of the array, use the shift function, like this
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.