Push/Pop!
Goals:
- Add and remove elements to and from arrays using
push
andpop
.
Coding Snippets:
- Creaty empty arrays using bracket notation.
push
adds an element to the end of an array.pop
removes the last element from an array.- Every array has a
length
property which reveals how many elements it contains.
Math and Computer Concepts:
- Through the use of iteration, we can generate a large number of items programmatically using very few lines of code. The Array object's
push
function allows us to store these items so we can refer to them later, without explicitly creating a variable name for each one. push
andpop
are particularly useful for storing information that arises over the course of a program when you don't know how many items will be created, such as for capturing user input.- To avoid runtime errors, it's helpful to access an array's
length
property to verify that it is non-empty before usingpop
to remove an element. The example on the right effectively does this, as it uses a while loop to remove all elements of an array calledmoves
.
Activities:
Save each of the following in a folder called PushPop.
- RainbowMakers: iterate over an array of the ROYGBIV colors to create an array of eight turtles using
push
. Then iterate over this array of turtles to draw all eight stripes simultaneously. - Backtracker: make a turtle walk randomly around until it walks off the screen, recording it's moves along the way in an array using
push
. Then access these values in reverse usingpop
to have the turtle retrace its steps, back to its starting position. - UniqueRandNum: create an array of unique random values by testing each randomly selected value before adding to the array using
push
. Note that CoffeeScript facilitates checking if a valuen
is in an array of valuesnumbers
using thein
operator.n in numbers
is a boolean expression that you can use in awhile
loop to instruct the computer to keep drawing new random numbers until you find one that has not already been chosen. Display your set of unique values graphically. - LuckyStreak: revisit the LuckyStreak program from the Conditional Logic! lesson. This time, use
push
to add new sprites (for the coins) to an array. As you add additional coins, iterate over the array to move the existing coins over.