JavaScript Functions

What is a Function?

In addition to variables, functions are an essential building block of modern programming languages. A function is a piece of code that performs a certain task when it is called. Functions can do any of the following things:

Here's an example of a function that simply prints text to the console:

function printMessage() {

  console.log("The Adventures of Buckaroo Banzai Across the 8th Dimension");

}

And then we call the function like this:

printMessage();

Copy this function and the function call into your HTML document between the script tags and refresh the page. Then open the console and check the result.

Passing Parameters

Functions can accept values (parameters), which are then stored in local variables. A local variable is just a variable that is only declared within the scope of the function. The following is an example of a function that prints the sum of two values passed in as parameters:

function printSum(numberOne, numberTwo); {

  console.log(numberOne + numberTwo);

}

Then we can call the function like this:

printSum(5, 10);

Or like this:

var x = 5;

printSum(x, 10);

Try writing your own function that subtracts two numbers passed into it and prints the result to the console.

Returning Values

In addition to accepting and processing information, functions can also return values. This allows us to integrate functions into our code and make it more versatile, efficient, and elegant. Let's take a look at an example:

function double(number) {

  return number * 2;

}

Then when we call the function, we can do different things with the result. Like print it to the console:

console.log(double(5));

Or store it in a variable:

var result = double(5);

Or even pass it into another function:

printSum(5, double(5));

Try writing a function that finds the quotient of two numbers. Then call that function and print the result to the console.

The JavaScript Library

You may have noticed that we've already used functions in previous lessons. In the last lesson we passed a string as a parameter into the getElementById function, which returned the element so that we could manipulate it. This function, in addition to many others, is part of the default JavaScript library. These functions can perform a number of useful tasks:

Consult the JavaScript application programming interface (API) documentation for more information on these functions.

Make sure you can effectively read and write functions before moving on to the next lesson.

Continue to Next Lesson »