Reading from
Javascript & jQuery: The Missing Manual
- Functions (pp 100 - 114).

For more interactive examples, check the W3Schools pages: Functions.

For a more in-depth discussion of functions and using objects with functions, read Chapter 4 of*Head First HTML5 Programming.*

For more interactive examples, check the W3Schools pages: Functions.

For a more in-depth discussion of functions and using objects with functions, read Chapter 4 of

As you know, in Mathematics, functions are an important concept that refer
to the *relation between a set of inputs and a set of outputs, so that every
input has exactly one output*. A well-known example is the function that
relates every real number *x* to its square *x ^{2}*.
If the output is named
y and the input x, one can write their relation as

A function can be represented through a formula (usually in math), an algorithm (in programming), or other ways (tables, graphs, etc., not relevant to us). How a function is represented is not always important, what matters is that such a representation allows us to map every input to an output, over and over again.

We can see this principle in the Pythagorean theorem shown below. If we want to calculate the hypotenuse of many right triangles, we can write a computer program to do that, by exploiting the fact that the hypotenuse is a function of the two triangle sides (catheti).

The Javascript function we can write to calculate the hypotenuse and the calculation results
for the three triangles shown in the image are given below.
**Open the console** in your browser and then
click the "Execute it" button.

The following image from the *Head First HTML5* book summarizes what goes into
a function definition.

Notice how the variables `level`

and `score`

in the function definition
`addScore`

are called **parameters**. However, when we invoke the
function like in:

`addScore(3, 10)`

or `addScore(6, 20)`

**You define a function with parameters, you call a function with arguments.**

Other important things to remember:

- A function can have zero parameters. You still have to use the parentheses to define it.
- A function might have no
`return`

statements. In this case we say that the function returns*undefined*.

In the diagram below, we show all possible ways in which a function can be defined. As you
can imagine, *input* corresponds to *parameters* and *output* to
*returned values*

A) function has parameters and return value

B) function has no parameters, but has return value

C) function has parameters and no return value (but produces side effects)

D) function has no parameters and no return value (but produces side effects)

After discussing methods as a special kind of functions, we will look at a group of functions to categorize them in one of the four groups shown in the graphics.

From what we have seen so far, we can say that a function is a block of code that has a name, that requires zero or more parameters, may return a value or not, and can be invoked an unlimited number of times taking as many arguments as needed. Based on this definition, what do you think of the following code examples?

document.querySelector("nav"); var today = new Date(); today.getFullYear(); var myClasses = ["JPN101", "ECON101", "CS110"]; myClasses.push("MATH116"); myClasses.sort(); myClasses.push("ART101"); myClasses.sort();

All the methods indeed conform to the function description: they have a name, they may return a value, and we can invoke them several times with different arguments. (Since these are methods defined by Javascript, we don't see the parameters, but the fact that we can call them with arguments, indicates that there are parameters in their definition)

Syntactically, we can tell functions from methods apart because a method is **usually**
invoked using the dot notation:

objectName.methodName(Without such a notation, the Javascript interpreter will complain that it doesn't recognize the method name. Also, it will not make sense to use these methods without an object. What is the thing we would like to sort, if we simply writeoptional parameters);

`sort()`

? By providing the object name, we are also providing
the context (object state) within which the method will operate (either by changing this state, or querying it).
We emphasized the word **usually** above, because there are special cases in
Javascript where methods are invoked without the dot notation. This is done to simplify writing
code. In fact, many of the built-in functions we have been using so far, such as:
`alert`

, `prompt`

, `confirm`

are actually methods of the object
`window`

. The object `window`

represents the open window on the browser,
where our HTML code is being rendered. You can verify that `alert`

, etc. are methods
by typing on the console: `window.alert()`

. To read more about this object,
refer to the Window object notes on W3Schools.

We have seen variables in many contexts so far. Here is a summary:

var age = prompt("How old are you?"); //at the program levelfor (var i = 0; i < 5; i++) {alert("i="+i);}; //inside a for loopfunction addScore(level, score) { }; //as parameters in a function definitionfunction displayDate(){ var today = new Date(); //inside the body of a functiondocument.querySelector("#date").innerHTML = today.toLocaleDateString(); }

No matter where in the program we define them, variables work always in the same way:
they reserve some place in the computer memory where they store their value and
provide a name in able to refer to that value later on. However, the location in
the program where we define a variable influences its visibility by other parts
of the program. In fact we will be distinugishing betwen *global variables*
and *local variables* in the following way:

If a variable is defined outside a function, it's GLOBAL, if it's declared inside a function, it's LOCAL.

Thus, in the examples shown above, the variables `age`

and `i`

are global, because they are outside any function. While the variables
`level`

, `score`

, and `today`

are local.

Knowing where a variable is defined allows us to know its **scope**,
that is, where the variable is visible or not. Local variables are visible (or exist)
only within the body of the function where they were defined. Global variables are
visible everywhere in the program. What this means is that while we can refer to
global variables everywhere by their name and expect to get their value back, we
will be able to refer to local variables only within the body of their function.
Attempts to refer to them from outside the function will result in the Javascript
error message: *ReferenceError: variableName is not defined*.

To get a more in-depth understanding for the differences between global and local variables, read pages 123-127 of the recommended reading.

In the following, there is a variety of function and method calls/definitions. Using the four groups of functions depicted in Figure 4, assign each of these functions/methods to one of the four groups.

var age = prompt("How old are you?"); // prompt alert("You are " + age + " old."); // alert function displayDate(){ // displayDate var today = new Date(); document.querySelector("#date").innerHTML = today.toLocaleDateString(); } document.querySelector("#date"); // querySelector Math.random(); // random function isEligibleToVote(age, citizenship){ //isEligibleToVote if (age < 18) {return false;} else { if (citizenship == "US") {return true;} else {return false;} } } function allowInBar(){ // allowInBar var birthdate = prompt("Enter your birthdate (e.g., 03/29/1994)"); var age = Math.floor((new Date() - new Date(birthdate))/(365*24*3600*1000)); if (age < 21) {return false;} else {return true;} }