[prev]Functions[next]

Up until now, we've been using code such as print or printp and calling these "commands." They are actually examples of a more general programming construct called functions. In this lesson, we are going to teach you how to define your own functions!

Example: Shouting

Here we create a function named "shout" that prints a string in all capitals:

 
1
2
3
4
5
6
7
function shout(text) {
  var upperText = text.toUpperCase()
  printp(upperText)
}
shout("Wow, functions are useful.");
shout("I could do this all day.");
shout("Now my throat hurts.");

Click to run the code.

Exercise: Shout in bold. Change the above program to use the HTML bold tag (<b>) to shout even "louder."


Any kind of code that you are already familiar with can go inside a function, but it will only run when the function is called. The following example uses a for-loop inside a function.

Example: Multiprint

Here we define a new function called "multiprint" that uses a for-loop inside it.

 
1
2
3
4
5
6
7
function multiprint(count, message) {
  for (var i = 0; i < count; i++) {
    printp(message)
  }
}
multiprint(10, "I will not throw " +
               "paper airplanes in class.")

Click to run the code.

Line 1 in the is called the function "signature". It indicates how many "arguments" the function has and what to name those arguments. Those names are available for use within the function.

Exercise: Multiprinting user input. Write a program that uses the form function we learned about earlier to ask the user for a message and the number of times to repeat it, and then calls multiprint with the appropriate arguments. (See this app for the solution if you are stuck).

Anatomy of a Function Definition

Defining a function.

In the function defined above, any code in the body that refers to either count or message will see the arguments the function is called with.

Note: Overriding and "shadowing" variables.

There is some trickiness in dealing with variables names in functions. For example, what happens if you already have a variable called count and then define a function that has count as an argument? In that case, the references inside the function to count reach the argument, not the count that's defined outside the function. (In fact, the function can't access the outside count at all, and we say the outside variable is "shadowed" by the inside variable.)

Another way to shadow a variable inside a function is to declare it using the var keyword. Declaring var x = 5 inside a function means that you can refer use x and get the value 5 inside that function, regardless of whether there is another variable named x outside the function. It's generally a good idea to use the var keyword for variables declared inside functions.

Variables defined outside a function which are not shadowed, are still available and modifyable from inside a function.

These rules are called "scoping" rules, and they control which variables are visible in which "scopes". The JavaScript language uses what's called "static scoping" — see this wikipedia article for more information.

Example: Array's forEach

Some functions even take functions as arguments. A feature unique to JavaScript and a few other high-level languages is the ability to store functions in variables and pass them around. For example, arrays have a forEach method whose single argument is itself a function. This lets us do something to each element in an array without having to write a loop.

 
1
2
3
4
5
6
7
8
9
var bands = [ "Fall Out Boy", "Usher", 
              "Linkin Park", "Ne-yo",
              "Alicia Keys" ]

function critiqueBand(band) {
  printp(html("<i>"+band+"</i> kinda sucks."))
}

bands.forEach(critiqueBand)

Click to run the code.

This example passes a function (critiqueBand) as an argument to another function (bands.forEach).

Commands, functions, properties, and methods.

The terminology surrounding objects and functions is rather confusing. Let's clear things up:

  • command: This is an informal term that we have been using to describe function calls before we taught the details of functions. command == function.
  • property: A property is any named part of an object. Properties can hold values of various types, such as a string, a number, or even a function. property == any named part of an object.
  • method: When an object's property is a function, it is called a method of that object. For example, param is a method of the request object, which is why you can call the request.param() function in your code. method == function property of an object.
Previous Lesson: Objects Next Lesson: Function Results