< JavaScript

Functions

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. Parameters or arguments can be used to provide data, which is passed to a function to effect the action to be taken. The Parameters or arguments are placed inside the parentheses, then the function is closed with a pair of curly braces. The block of code to be executed is placed inside the curly braces. 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. 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"]);

Examples

Basic example

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!"

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!"

In the following example, the function hello does "understand" whether it is called with a parameter 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 arguments

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 calling a function within an html 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 is called with an argument of 6.

See Also

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.