Last modified on 25 March 2015, at 14:22

JavaScript/Functions

Previous: Control Structures Index Next: Anonymous Functions

FunctionsEdit

A function is an action to take to complete a goal, objective, or task. Functions allow you to split a complex goal into simpler tasks, which make managing and maintaining scripts easier. A parameter or argument is data which is passed to a function to effect the action to be taken. Functions can be passed zero or more arguments. A function is executed when a call to that function is made anywhere within the script, the page, an external page, or by an event. Functions are always guaranteed to return some value when executed. The data passed to a function when executed is known as the function's input and the value returned from an executed function is known as the function's output.

A JavaScript function is a code-block that can be reused inside an HTML document. A function created in another file cannot be included for reuse. The function can be called via an event, or by manual calling.

Functions can be constructed in three main ways. We begin with three "Hello, World!" examples:

Way 1 Way 2 Way 3
function hello() {
  alert("Hello, World!");
}
var hello = function() {
  alert("Hello, World!");
};
var hello = new Function(
  'alert("Hello, World!");'
);

Each function:

  • can be called with hello()
  • does not expect any arguments
  • performs an action to alert the user with a message
  • undefined is returned when execution is finished

The hello function can be changed to allow you to say hello to someone specific through the use of arguments:

Way 1 Way 2 Way 3
function hello(who) {
  alert("Hello, " + who + "!");
}
var hello = function(who) {
  alert("Hello, " + who + "!");
};
var hello = new Function('who',
  'alert("Hello, " + who + "!");'
);

Each function:

  • can be called with hello()
  • expects one argument to be passed
  • performs an action to alert the user with a message
  • undefined is returned when execution is finished

Each function can be called in several ways:

Way 1 Way 2 Way 3
hello("you");
hello.call(window, "you");
hello.apply(window, ["you"]);

ExamplesEdit

Basic exampleEdit

function myFunction(string) {
  alert(string);
  document.innerHTML += string;
}
myFunction("hello");

The example would first:

  • Define the myFunction function
  • Call the myFunction function with argument "hello"

The result:

  • An alert message with 'hello'
  • The string 'hello' being added to the end of the document's/page's HTML.

"Hello World!"Edit

Let's put together the "Hello World!" code from above on a sample Web page. The page calls the function once when the page is loaded, and whenever a button is clicked.

<html>
  <head><title>Some Page</title></head>
  <body>
    <button id="msg">greeting</button>
    <script type="text/javascript">
      function hello() {
        alert("Hello World!");
      }
 
      document.getElementById("msg").onclick = hello;
 
      hello();
    </script>
  </body>
</html>

Extended "Hello World!"Edit

In the following example, the function hello does "understand" whether it is called with a parametre or not, and returns the greeting with this parametre, or with the word "World":

<!DOCTYPE html>
<html>
  <head><title>Extended Hello World!</title></head>
  <body>
    <button id="msg">greeting</button>
    <script type="text/javascript">
      function hello(who) {
        if ((who == null)
         || (who.toString().search("object") >= 0)) {
 
          who = "World";
        }
        alert("Hello " + who + "!");
      }
 
      document.getElementById("msg").onclick = hello;
 
      hello("guy");
    </script>
  </body>
</html>

Functions with argumentsEdit

Let's start with a quick example, then we will break it down.

function stepToFive(number) {
  if (number > 5) {
    number -= 1;
  }
  if (number < 5) {
    number += 1;
  }
  return number;
}

This program takes a number as an argument. If the number is larger than 5, it subtracts one. If it's smaller than five it adds one. Let's get down and dirty and look at this piece by piece.

function stepToFive(number) {

This is similar to what we've seen before. We now have number following the function name. This is where we define our arguments for later use, which is similar to defining variables, except in this case the variables are only valid inside of the function.

  if (number > 5) {

If statements. If the condition is true, execute the code inside the curly brackets.

  number -= 1;

Assuming that JavaScript is your first language, you might not know what this means. This takes one off from the variable number. You can think of it as a useful shorthand for number = number - 1;.

  number += 1;

This is similar to the last one, except that it adds one instead of subtracting it.

  return number;

This returns the value of number from the function. This will be covered in more depth later on.

Here is an example of using this in a page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
 <head>
  <title>Some Page</title>
    <script type="text/javascript">
      function stepToFive(number) {
        if (number > 5) {
          number -= 1;
        }
        if (number < 5) {
          number += 1;
        }
        return number;
      }
    </script>
  </head>
  <body>
    <p>
      <script type="text/javascript">
        var num = stepToFive(6);
        alert(num);
      </script>
    </p>
  </body>
</html>

There are a few more things to cover here.

var num = stepToFive(6);

This is where the return statement in the function comes in handy. num here gets assigned the number 5, since that is what stepToFive will return when it's given an argument of 6.


Previous: Control Structures Index Next: Anonymous Functions