Feb 112013
gumball machine

A function is like a gumball machine

In reality, you’ve been using functions all your life.  A function is like a gumball machine.   There are 3 parts to every function: an input, a process, and an output.  In the case of our gumball machine:

  • input: a coin
  • process:  turn the handle, the machine deposits the coin in a repository, the machine opens a door, gumballs fall through the door, the door closes.
  • output: gumballs!

What other examples of functions can you think of that you’ve seen in real life?

A function, as defined in code, might look like this:

//define a function
function secretNumber(yourNum:Int) {
var yourNewNum = 100*((yourNum*7)/58);
return yourNewNum

//now we need to call the function to use it (so far, it's just been defined, but never used)
alert("Your secret number is "+secretNumber(4));

In the above code, the input was the variable yourNum; the process was to multiply that by 7, divide the product by 5, and then multiply that quotient by 100; the output returned the new number to you.


If I asked you to put a telephone into the gumball machine, you’d think I were crazy. Why? Because it’s not the right type of input. This machine only accepts the type of object that is a coin. Computer programs work the same way. A function is expecting a particular type of data. In our secretNumber function, we can see that an integer is required. Had we tried to use a string, the function would have failed. There are many different types in programming. Some of the more common types are:

  • string

    : a series of characters (letters, numbers, symbols). Typically, they are included in either single or double quotes.

  • integer

    : a whole number (no decimals!). If you include a decimal, the number will be cut off at the decimal point (not rounded). Can be used for arithmetic operations.

  • number (or floating point number)

    :a number with decimals.

  • array

    :A list of items. An array is different depending on the language. In javascript, an array is an indexed list of items. For each index, there is a value. Let’s consider that we have an array called “months.” At index 5, the value would likely be the 6th month, June (in javascript, array indices start at 0).

  • Object

    : An object is like an array; only, instead of having a numerical index, we find the value of specific properties by referring to their keys. Suppose we had an object named Person. In javascript, we can create a property of person as a key of that object, like so:

    Person.name = "Peter"

    The key is “name” and the value of that key is “Peter”. Objects exist in many languages and are similar to other types, such as: a hash, an associative array, a table, a list, a map, a dictionary.

Sorry, the comment form is closed at this time.