` Javascript #5 Function

From last class

Functions (remember this?) (p85)





You've been using built-in functions. Now you will learn how to define your own functions.

The idea behind functions is that you want to write some block of code (function) once and reuse it. The basic structure for defining a function looks like this:


  function functionName(){
    // javascript code you want to run
    // ...
    // ...
  }

- The keyword function lets the interpreter know you are creating a function.
- You provide a name for this function (eg. functionName)
- A pair of parenthesis which we will use later. It also is an indicater that it is a function
- Open curly brace and close curly brace marks the beginning and end of a block of code that makes up the function.


Here the name of the function is printToday. It has two lines of JavaScript code. Usually you put the function at the beginning of a script. Note that it will not run when it is created/defined. You need to call it.

function printToday(){
  var today = new Date();                       // create a Date object and put it into the variable today
  document.write(today.toDateString() + " ");   // convert to string the date represented by variable today 
  document.write(today.toTimeString());         // convert to string the time represented by variable today 
  document.write("<br>");
}


Example: 05_function.html
<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>

<script>
function printToday(){
  var today = new Date();                       // create a Date object and put it into the variable today
  document.write(today.toDateString() + " ");   // convert to string the date represented by variable today 
  document.write(today.toTimeString());         // convert to string the time represented by variable today 
  document.write("<br>");
}
</script>

</head>

<body>
This is the body. <br>


<script>
printToday(); // calling a function
</script>

</body>
</html>


Another example

<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
function printHello(){
  document.write("hello <br>");
}
</script>
</head>


<body>

<script>
  printHello();
  printHello();
  printHello();
  printHello();
</script>


</body>
</html>


Notes

Parameters/Arguments

Let's imagine that we want to customize the behaviour of your function. Functions can accept information through parameters. I often call them arguments.

Example: 05_functions4.html


You are not limited to passing one parameter. You can pass any number of parameters by separating them with a comma

Example: 05_functions5.html



So a general form for defining a function looks like this:

 
function functionName(parameter1, parameter2, parameter3,...) {
  // javascript code
}


To call (use) the function, you call with the same number of arguments (parameters) in the same order.

functionName(parameter1, parameter2, parameter3, ...);
Notes

Returning

You can retrieve information back from a function after you call it. You may have seen it used before like this

var answer = prompt("What is your name?");

This is called, returning a value. If the user typed in "Reed", the function prompt will return the string "Reed". You can think of returning as the function turning into that value being returned like this

var answer = "Reed";


To return a value from your own function, use the keyword return followed by the value you want to return.

function functionName(paramater1, parameter2) {
  //java script code
  return somevalue;
}


Example: 05_functions6.html
<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
// name is a parameter and can be used just a variable
var TAX= .08; // 8% sales tax

function calculateTotal(quantity, price){
  var total = quantity * price * (1 + TAX);
  return total;
}
</script>
</head>


<body>

<script>
   var salesTotal = calculateTotal(3, 15);
   document.write("Total price: $" + salesTotal + "<br>");
</script>

</body>
</html>


Another example of returning. In this case, a radom color


<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
/*  A function that generates random color found on the Internet */
function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}
</script>

</head>
<body>
<script>
document.body.style.backgroundColor = get_random_color();
</script>
</body>
</html>


Notes

Keeping Variables from Coliding: Scope of a variable (p92)







Variables have what is called a "scope". It indicates the visibility of the variable.
If a variable is created outside a function, it can be seen globally from anywhere in the script. It is called a global variable. Variable j is a global variable.

If a variable is created as part of a function (either as an argument/parameter or inside a function), the variable can only be seen inside the function and it takes precedent over global variables. These are called local variables. Variable i is a local variable and can be seen (accessed) only from within the function warning().

The variable name "message" is used outside of the function and also inside a function. This will be treated as separate variables. One as a local variable within the function warning, and the other a global variable. You cannot access the global variable 'message' from within the function since the local variable inside the function overlaps.
Notes

Lab

Read Ch3 of textbook.

1. Finish MM Ch3:Tutorial: A Simple Quiz. E-mail code with each line commented with explanation of what it is doing. Be precise in naming things (an array, variable) and explaining its actions.


Notes