Functions

The big picture




General syntax for defining your own function

  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 several 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 with the definition of a function and a example calling that function. Note that the definition is in the <head> section. This is to ensure that the definition is available when the rest of the document loads.
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>





In the previous example, the function printToday is run when the page is loaded. If we want the function to run when a button is clicked, we can use the onClick event handler like this:
<!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>

<input type="button" value="click me" onclick="printToday()" />

</body>
</html>





Another example. What will this do?

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


<body>

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


</body>
</html>


Notes

(Built-In) Functions and methods

You've been using functions that were provided to you. It is defined somewhere. Some are built-in. Some are part of an object (like window or document). When a function belongs to an object, we call it a method. So window.alert() or document.write() is a method. (It's not that important in terms of use, but people call it different so you should know).

   window.alert();

   document.write();      // Writes HTML or JavaScript code to a document
   
   prompt();              // Displays a dialog box that prompts the visitor for input

   decodeURI();           // Decodes a URI

   back();                // Loads the previous URL in the history list
 
   ceil();                // Returns x, rounded upwards to the nearest integer

   click();               // Simulates a mouse-click on an element

   getDate();             // Returns the day of the month (from 1-31)
   
   scrollBy();            // Scrolls the document by the specified number of pixels

   sqrt();                // Square root           y = sqrt(x)
   

are all functions. You can identify a function/method by the use of parenthesis.
(See W3schools JS Reference for a list)

Notes

Passing Arguments

Often, you pass an argument to the function inside the parenthesis.

   alert('hello world');
Arguments allow you to extend or change the behavior of functions by passing information to it.
Notes

Arguments

Let's imagine that we want to customize the behaviour of your function. Functions can accept information through arguments. Example: 05_functions4.html


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

Example: 05_functions5.html



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

 
function functionName(var1, var2, var3) {
  // javascript code
}


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

functionName(argument1, argument2, argument3);
Notes

Passing Variables

Here is another example. Notice here that a variable is used as an argument to the function "area".
<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
function area(x, y){

   alert(x * y);
}
</script>
</head>


<body>

<script>
  var length = 3;
  var width = 5;  
  area(length, width);


  area(length, 10);
</script>


</body>
</html>
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(argument1, argument2) {
  //java script code
  return somevalue;
}


Here is an example
<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
function area(x, y){
  var a;
  a = x * y;  
  return a;
}
</script>
</head>


<body>

<script>

  var b;
  b = area(3, 10);
  
  document.write(b);
</script>

</body>


Example: 05_functions6.html
<!DOCTYPE html>
<html>
<head>
<title> The Title of this HTML Page </title>
<script>
// name is a argument 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

Anonymous Function

You'll see an alternative way of defining functions without names used often. They are called anonymous functions.
var sayHello = function(){ alert("Hello"); }; 
Notes