Javascript Functions Tutorial

In this Javascript tutorial we learn how to group sections of our code into smaller, reusable units, with functions.

We cover how to create (define) a function, use (call/invoke) a function, how to add parameters and return a value.

We also cover arrow functions which are similar to anonymous functions/lambdas.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a function

A function is a way for a developer to group sections of their code into smaller, reusable units.

As an example, let’s consider some simple functionality.

Example:
<script>

  // number to check
  var num = 5;

  // if the number can be divided by two
  // without a remainder, it's an even num
  if (num % 2 == 0) {
    document.write(num, " is an even number");
  } else {
    document.write(num, " is an odd number");
  }

</script>

The example above will check if a provided number is even or odd.

We may have to perform this check multiple times throughout our code. We don’t want to repeat ourselves and retype the logic each time.

We want to separate the logic into a reusable unit that we can more easily use over and over, anywhere in our code. That’s where functions come into play.

How to create (define) a function

A function consists of the following parts.

  • The function keyword.
  • A name.
  • A parameter list (optional).
  • A body with one or more statements.
  • A returned value (optional).
Syntax:
function name(parameters) {

  // one or more logic statements

  return value;
}

This is known as a function definition and it can be simple or complex. Let’s start with the most basic function and add features as we need them.

Example:
<script>

  function logger() {

    document.write("Hello World");
  }

</script>

In the example above, we create a function called logger. All it does is execute the document.write() statement to log a message to the page.

When we open the page in our browser, nothing happens. We’ve defined the function, but we haven’t actually used it yet.

How to use (call) a function

To use a function, we need to tell the translator that we want the function to execute its code once. We do this by calling (invoking) the function.

To call a function we write its name, followed by what’s known as arguments for any parameters it needs, between parentheses. Because the call doesn’t have a closing curly brace, we also need to terminate the statement with a semicolon.

Syntax:
// definition
function name(parameters) {
  // function body
  return value;
}

// call
name(arguments_for_parameters);

As an example, let’s use our simple logger function from the previous section.

Example:
<script>

  // call
  logger();

  // definition
  function logger() {

    document.write("Hello World");
  }

</script>

When we run the example above, the words “Hello World” are printed to the screen.

It should be noted that even though we don’t have any parameters, and therefore don’t need any arguments, we still need to add the parentheses in both the definition and the call.

We can also call a function anywhere in the document, it doesn’t have to be below the function definition.

How to add parameters to a function

At this point our logger function isn’t very useful, it only prints “Hello World” to the screen. We can make it so that the function prints any message we want.

A parameter is simply a temporary variable that we can use inside the function’s body. The translator will replace every occurance of the parameter in the definition, with whatever we specify as an argument in the call.

Syntax:
// definition
function name(x) {

  // use x here
}

// call
name(value_to_replace_x);

We’ll use our simple logger function again.

Example:
<script>

  logger("Hello World");

  function logger(msg) {

    document.write(msg, "<br>");
  }

</script>

This time, we’ve added the parameter msg in the function definition. We’ve also placed the parameter as the message that the document.write() statement will print to the page.

In the function call we specify the words “Hello World” as the argument. The translator will replace the temporary variable msg with the words everywhere it occurs in the function body.

When we run the example, the words “Hello World” appears on the screen, exactly the same as before. The difference is that now we can choose the message each time we call the function, it’s not hardcoded into the function definition anymore.

As an example, let’s call the function a few more times with different messages as the argument.

Example:
<script>

  logger("Hello World");
  logger("Lovely weather we are having");
  logger("I hope it stays this mild");

  function logger(msg) {

    document.write(msg, "<br>");
  }

</script>

When we run the example above, all three messages are printed to the screen.

How to add multiple parameters to a function

Javascript doesn’t limit us to a single parameter in our functions, we can have as many as we need.

To add more parameters, we simply write them to our list, separating each with a comma.

Syntax:
function name(param_1, param_2) {
  // function body
}
Example:
<script>

  logger("<strong>", "Bolded text", "</strong>");
  logger("<p>", "Text inside a paragraph", "</p>");

  function logger(prefix, msg, postfix) {

    document.write(prefix);
    document.write(msg);
    document.write(postfix);
  }

</script>

In the example above, we add two more parameters, prefix and postfix, meant to help us with the formatting of our log message.

How to return a value from a function

Functions have another ability, they can return a value when called.

As an example, let’s consider a simple math function that adds two numbers together. We may not want to print that value to the page directly from inside the function, but use it for other calculations somewhere else in our application.

We can return the value from the function and either use it directly, or store it in a data container for later use.

To return a value, we write the return keyword, followed by the value we want to return and a semicolon to terminate the statement.

Syntax:
function name(parameters) {

  // function body

  return value;
}
Example:
<script>

  // use the value directly
  document.write( add(5, 3) );

  // or store the value
  result = add(5, 3);

  function add(num_1, num_2) {

    return num_1 + num_2;
  }

</script>

The example above will add num_2 to num_1 and return the result when the function is called.

We call the function twice here to demonstrate that it can be used directly in something like the document.write() statement, or we can assign the returned value to a variable to store it.

Arrow (anonymous/lambda) functions

A function expression, more commonly known as an arrow function, is a shorthand method of writing a function.

These are similar to lambdas/anonymous functions in other languages like C#.

Let’s see the syntax first, then break it down.

Syntax:
// definition
var name = (parameters) => {
  // function body

  return value;
}

// call
name(parameters);

We don’t use the function keyword or give it a name, we assign the function to a variable instead. The variable will act as the function name and is used to call it.

We also add the => (fat arrow) before the function body. The rest of the function is the same as a traditional function.

As an example, let’s consider a simple function that greets a user.

Example:
<script>

  // traditional function definition
  function greeting(name) {

    document.write("Hello, ", name);
  }

  // traditional function call
  greeting("John");

</script>

The example above will print a hello message to the page when called. Now lets convert this into an arrow function.

Example:
<script>

  // arrow function definition
  var greeting = (name) => {

    document.write("Hello, ", name);
  }

  // arrow function call
  greeting("John");

</script>

We can simplify the arrow function above even more. When an arrow function only has a single statement in its body, we can remove the curly braces.

Example:
<script>

  // arrow function definition
  var greeting = (name) => document.write("Hello, ", name);

  // arrow function call
  greeting("John");

</script>

If the arrow function returns a value, and the return statement is the only statement in the body, we can omit the return keyword as well.

Example:
<script>

  // this function
  var greeting = (name) => {
      return "Hello, " + name;
  }

  // becomes this
  var greeting = (name) => "Hello, " + name;


  document.write(greeting("John"));

</script>

Let’s see another example of a simple arrow function.

Example:
<script>
  // log something to the page
  var logger = (msg) => document.write("<p>", msg, "</p>");

  // add two numbers together
  var add = (num_1, num_2) => num_1 + num_2;

  logger(add(5, 8));
  logger(add(-2, 44));
  logger(add(815, -20589));

</script>

Arrow functions also handle the this keyword differently. We cover it in later on in the course, once we know more about objects.

Mini challenge

Now that we know more about functions, try to convert the following function (from the start of the tutorial) into both a traditional and an arrow function.

Logic:
// number to check
var num = 5;

// if the number can be divided by two
// without a remainder, it's an even num
if (num % 2 == 0) {
    document.write(num, " is an even number");
} else {
    document.write(num, " is an odd number");
}

If you get stuck, see our solution below.

Solution:
<script>
  // traditional function
  function is_even(num) {

    if (num % 2 == 0) {
      document.write(num, " is an even number<br>");
    } else {
      document.write(num, " is an odd number<br>");
    }
  }

  is_even(5);
  is_even(8);

  // arrow function
  var is_odd = (num) => {

    if (num % 2 != 0) {
      document.write(num, " is an odd number<br>");
    } else {
      document.write(num, " is an even number<br>");
    }
  }

  is_odd(-2);
  is_odd(14);
  is_odd(7);

</script>

How to create on-click functions

We can run custom functions when a user clicks on an element, like an html button. This is useful for something like hiding/displaying a menu.

To do this we create an onclick event in html, and then specify the function we want to run.

Syntax:
<htmltag onclick="function_to_run()"></htmltag>
Example:
<script>

  function alert_user() {

    alert("Hello there");
  }

</script>


<input type="button" value="Click Me" onclick="alert_user()"/>

In the example above, we run the function that shows an alert to the user as soon as they click on the button.

There are multiple ways to generate click events, like the event listener, which we cover later in the course.

Summary: Points to remember

  • Functions group our code into smaller reusable units, and are usually responsible for only a single specific task.
  • It’s not enough for a function to be defined, we must call (invoke) it in order to use it.
  • Functions accept one or more parameters that allow different inputs to be used on each call of the function.
  • Functions can return a single value with the return keyword.
  • Arrow functions are a shorthand syntax of writing a function and simplifies the process.
    • If an arrow function only contains a single statement in its body, the curly braces may be omitted.
    • If an arrow function returns a value, and the return statement is the only one in its body, both the return keyword and the curly braces may be omitted.