PencilCoder

Callbacks!

Goals:

  • Use functions as objects, passing them to other functions as callbacks

Coding Snippets:

  • coding snippets
  • The spiro function creates a spirograph using n repetitions of any shape. It expects the directions for that shape to be passed to it as an argument, which it internally referes to as drawShape.

  • The function containing the instructions expected by spiro (in this case, drawSquare) is known as a callback.

Math and Computer Concepts:

  • Functions are a special type of object representing computations to be performed. Because they are objects, we can work with functions much like we would any other data type: they can be assigned to variables, stored in collections such as arrays, and, the focus of this lesson, passed to other functions as arguments.
  • A callback is a function passed to another for the purpose of being called back, by that other function, at some later time.
  • Callbacks are an extremely valuable programming tool. In this lesson, we will explore relatively basic examples. But in the next lesson, we will see how they are essential for making our programs interactive, i.e., input data from another source, accept user input, and more.

Activities:

Save each of the following in a folder called Callbacks.