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 anonymous and arrow functions as well as their expressions.

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.

Anonymous functions

An anonymous function is simply a function without a name.

Anonymous functions can either be used as a parameter for another function, or it can be turned into a function expression.

When we use it as an argument in another function, we simply omit the name.

Example:
<html>
<body>
  <button>Click Me!</button>

</body>

<script>
  const el = document.querySelector("button");

  // use an anonymous function as a parameter
  // for the 'addEventListener' method
  el.addEventListener("click", function() { alert("Alert!"); } );

</script>

</html>

In the example above, we use a function without a name as the second argument for the addEventListener() method.

If you don’t know about event listeners, don’t worry. We cover them in the Event Listeners lessonOpens up in a new page .

When we turn it into a function expression, we assign the anonymous function to a variable. The variable name will then act as the function’s name.

Syntax:
// definition
let variable_name = function(parameter_list) {
  // function body
}

// invocation
variable_name(arguments);
Example:
<script>
  // an anonymous function assigned
  // to a variable becomes a function
  // expression
  let alertMe = function() {
    alert("Alert!");
  }

  // the variable name then acts
  // as the function's name
  alertMe();
</script>

In the example above, we assign an anonymous function to the variable ‘alertMe’. Then we use the variable name with parentheses to invoke the function.

Arrow functions

An arrow function is a shorthand way to write an anonymous function.

We don’t use the function keyword, but we add what’s known as a fat arrow operator => between the parameter list and the code block.

Syntax:
(parameter_list) => {
  // function body
}

We also use arrow functions as parameters inside other functions.

Example:
<html>
<body>
  <button>Click Me!</button>
</body>
<script>
  const el = document.querySelector("button");

  // use an arrow function as a parameter
  // for the 'addEventListener' method
  el.addEventListener("click", () => { alert("Alert!"); } );
</script>
</html>

This time, we don’t use the function keyword and add a fat arrow between the parameter list and the function body.

Like anonymous functions, arrow functions can be turned into function expressions.

Example:
<script>
  // an arrow function assigned
  // to a variable becomes a
  // function expression
  let greeting = (name) => {
    alert("Hello " + name);
  }

  // the variable name then acts
  // as the function's name
  greeting("John");
</script>

In some situations, we can simplify the arrow function’s syntax.

When the function only has one statement in it’s body, we may omit the curly braces of the code block.

Example:
<script>
  // the function only has a single
  // statement so we may omit the
  // the curly braces
  let greeting = (name) => alert("Hello " + name);

  greeting("John");
</script>

When the function returns a value, and the return value is the only statement in the code block, we may omit the return keyword too.

Example:
<script>
  // we may omit the return
  // keyword if it is the only
  // statement in the function body
  let greeting = () => "Hello";

  alert( greeting() );
</script>

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

Javascript allows us to invoke functions when an event happens, like a user clicking on a button.

We can do this in several ways, all of them involving event listeners. An event listener will listen for a specific event, such as a click, in the document.

If you don’t know about event listeners, don’t worry. We cover them in the Event Listeners lessonOpens up in a new page .

1. Inline event handlers (bad practice)

An inline event handler invokes a function directly on an HTML attribute.

For example, if we wanted to listen for a click, we would use the onclick HTML attribute.

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

For the attribute’s value we can specify a function to run when the click event happens.

Example:
<script>
  function alert_user() {

    alert("Hello there");
  }
</script>


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

The function can also be run directly inside the attribute.

Example:
 <input type="button" value="Click Me" onclick="alert('Hello there');"/>

Inline event handlers are considered bad practice, developers don’t really use them anymore.

2. Event handler properties

Instead of the html attribute, we can use the element’s onclick property. This property contains the event handler code we need to listen for a click event on the element.

First, we need to get the element and store it so we can access the property.

Example:
// get the first button element in the document
const btn = document.querySelector('button');

Then we can access the onclick property with dot notation and use an anonymous or arrow function to specify what we want to happen when the element is clicked.

Example:
<script>
// get the first button element in the document
const btn = document.querySelector('button');

// invoke function when the
// event listener catches a
// click on the button
btn.onclick = function() {

  alert("Hello there");
};
</script>

We can use a named function instead of an anonymous or arrow function.

Example:
<script>
// get the first button element in the document
var btn = document.querySelector('button');

function clickAlert() {
  alert("Hello there");
}

// invoke function when the
// event listener catches a
// click on the button
btn.onclick = clickAlert;
</script>

Note that we don’t specify the parameter list in this case, rather we specify a reference to the function by omitting the parentheses.

If we did add the parentheses, Javascript would think it was a standard function call and would execute it without waiting for the event to fire first.

3. Event listener function

Javascript also provides us with the addEventListener() function that we invoke on the element object.

The function takes two arguments. In the first argument we specify the type of event we’re listening for and in the second argument we specify the function to invoke when the event fires.

Example:
<script>
// get the first button element in the document
var btn = document.querySelector('button');

function clickAlert() {
  alert("Hello there");
}

// add an event listener on the button,
// listening for a 'click' event and
// when the event fires, invoke the
// 'clickAlert' function
btn.addEventListener('click', clickAlert);
</script>

Again, we can use either a named function like above, or an anonymous or arrow function.

Example:
<script>
// get the first button element in the document
var btn = document.querySelector('button');

// add an event listener on the button,
// listening for a 'click' event and
// when the event fires, invoke the
// function
btn.addEventListener('click', () => { alert("Hello there"); });
</script>

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.
  • An anonymous function is a function without a name.
  • Arrow functions are a shorthand syntax of writing an anonymous function.
    • 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.