PencilCoder

Push/Pop!

Goals:

  • Add and remove elements to and from arrays using push and pop.

Coding Snippets:

  • 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 and pop 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.
  • Backtracker ExampleTo avoid runtime errors, it's helpful to access an array's length property to verify that it is non-empty before using pop 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 called moves.

Activities:

Save each of the following in a folder called PushPop.