The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Functions in JavaScript

by kirupa   |   filed under JavaScript 101

So far, all of the code we’ve written really contained no structure. It was just…there:

alert("hello, world!");

There is nothing wrong with having code like this. This is especially true if our code is made up of a single statement. Most of the time, though, that will never be the case. Our code will rarely be this simple when we are using JavaScript in the real world for real-worldy things.

To highlight this, let's say we want to display the distance something has traveled:

If you remember from school, the distance is calculated by multiplying the speed something has traveled by how long it took:

 

 

The JavaScript version of that will sorta look as follows:

let speed = 10;
let time = 5;
alert(speed * time);

We have two variables named speed and time, and they each store a number. The alert function displays the result of multiplying the values stored by the speed and time variables. This is a pretty literal translation of the distance equation we just saw.

Let’s say we want to calculate the distance for more values. Using only what we've seen so far, our code would look as follows:

let speed = 10;
let time = 5;
alert(speed * time);
 
let speed1 = 85;
var time1 = 1.5;
alert(speed1 * time1);
 
let speed2 = 12;
let time2 = 9;
alert(speed2 * time2);
 
let speed3 = 42;
let time3 = 21;
alert(speed3 * time3);

I don’t know about you, but this just looks turrible. Our code is unnecessarily verbose and repetitive. Like we saw earlier when we were learning about Variables, repetition makes our code harder to maintain, and it also wastes our time.

This entire problem can be solved very easily by using what we'll be seeing a lot of here, functions:

function showDistance(speed, time) {
	alert(speed * time);
}
 
showDistance(10, 5);
showDistance(85, 1.5);
showDistance(12, 9);
showDistance(42, 21);

Don’t worry too much about what this code does just yet. Just know that this smaller chunk of code does everything all those many lines of code did earlier without all of the negative side effects. We'll learn all about functions and how they do all the sweet things that they do starting...right...now!

Onwards!

What is a Function?

At a very basic level, a function is nothing more than a wrapper for some code. A function basically:

  1. Groups statements together
  2. Makes your code reusable

You will rarely write or use code that doesn't involve functions, so it's important that you get familiar with them and learn all about how well they work.

A Simple Function

The best way to learn about functions is to (in our usual style) just dive right in and start using them, so let's start off by creating a very simple function. Creating a function isn't very exciting. It just requires understanding some little syntactical quirks like using weird parenthesis and brackets.

Below is an example of what a very simple function looks like:

function sayHello() {
	alert("hello!");
}

Just having a function defined isn't enough, though. Our function needs to actually be called, and we can do that by adding the following line afterwards:

function sayHello() {
	alert("hello!");
}
sayHello();

To see all this for yourself, create a new HTML document (call it functions_sayhello.htm) and add the following into it:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Say Hello!</title>

  <style>

  </style>
</head>

<body>
  <script>
    function sayHello() {
      alert("hello!");
    }
    sayHello();
  </script>
</body>

</html>

If you typed all this in and previewed your page in your browser, you will see hello! displayed. The only thing that you need to know right now is that our code works. Let's look at why the code works next by breaking the sayHello function into individual chunks and looking at each in greater detail.

First, we see the function keyword leading things off:

This keyword tells the JavaScript engine that lives deep inside your browser to treat this entire block of code as something having to do with functions.

After the function keyword, we specify the actual name of the function followed by some opening and closing parentheses, ( ):

Rounding out our function declaration are the opening and closing brackets that enclose any statements that we may have inside:

The final thing is the contents of our function - the statements that make our function actually functional:

In our case, the content is the alert function that displays a dialog with the word hello! displayed.

The last thing to look at is the function call:

The function call is typically the name the function we want to call (aka invoke) followed again by the parentheses. Without our function call, the function we created doesn't do anything. It is the function call that wakes our function up and makes it do things.

Now, what we have just seen is a look at a very simple function. When a function is defined like this with the function keyword followed by a name, it is formally known as a function declaration. We may also see these types of functions referred to as a function statement or function definition. With the names and introduction out of the way, in the next couple of sections, we are going to build on what we've just learned and look at increasingly more realistic examples.

Creating a Function that Takes Arguments

The previous sayHello example was quite simple:

function sayHello() {
	alert("hello!");
}
sayHello();

We call a function, and the function does something. That simplification by itself is not out of the ordinary. All functions work just like that. What is different is the details on how functions get invoked, where they get their data from, and so on. The first such detail we are going to look at involves functions that take arguments.

Let's start with a simple and familiar example:

alert("my argument");

What we have here is our alert function. We've probably seen it a few (or a few dozen) times already. What this function does is take what is known as an argument for figuring out what to actually display when it gets called. Calling the alert function with an argument of my argument results in the following getting displayed:

an argument

The argument is the stuff between your opening and closing parenthesis when calling the alert function. The alert function is just one of many functions available to you that take arguments, and many functions you create will take arguments as well.

To stay local, just from this tutorial itself, another function that we briefly looked at that takes arguments is our showDistance function:

function showDistance(speed, time) {
	alert(speed * time);
}

See, you can tell when a function takes arguments by looking at the function declaration itself:

function showDistance(speed, time) {
	alert(speed * time);
}

What used to be empty parenthesis following the function name will actually contain some information about the quantity of arguments your function needs along with some hints on what values your arguments will take.

For showDistance, we can infer that this function takes two arguments. The first argument corresponds to the speed and the second argument corresponds to the time.

We specify your arguments to the function as part of the function call:

function showDistance(speed, time) {
	alert(speed * time);
}
showDistance(10, 5);

In our case, we call showDistance and specify the values we want to pass to your function inside the parentheses:

Because we are providing more than one argument, we can separate the individual arguments by a comma. Oh, and before I forget to call this out, the order you specify your arguments matters.

Let's look at all of this in greater detail starting with the following diagram:

example

When the showDistance function gets called, it passes in a 10 for the speed argument, and it passes in a 5 for the distance argument. That mapping, as shown in the previous diagram, is entirely based on order.

Once the values you pass in as arguments reach our function, the names we specified for the arguments are treated just like variable names:

We can use these variable names to easily reference the values stored by the arguments inside our function without any worry in the world.

Note - Mismatched Number of Arguments

If a function happens to take arguments and you don't provide any arguments as part of your function call, provide too few arguments, or provide too many arguments, things can still work. You can code your function defensively against these cases, and in the future, we will touch upon that a bit.

In general, to make the code you are writing more clear, you should provide the required number of arguments for the function you are calling.

Creating a Function that Returns Data

The last function variant we will look at is one that returns some data back to whatever called it. Here is what we want to do. We have our showDistance function, and we know that it looks as follows:

function showDistance(speed, time) {
	alert(speed * time);
}

Instead of having our showDistance function calculate the distance and display it as an alert, we actually want to store that value for some future use. We want to do something like this:

let myDistance = showDistance(10, 5);

The myDistance variable will store the results of the calculation the showDistance function does.

The Return Keyword

The way you return data from a function is by using the return keyword. Let's create a new function called getDistance that looks identical to showDistance with the only difference being what happens when the function runs to completion:

function getDistance(speed, time) {
	var distance = speed * time;
	return distance;
}

Notice that we are still calculating the distance by multiplying the speed and time. Instead of displaying an alert, we instead return the distance (as stored by the distance variable).

To call the getDistance function, we can just call it as part of initializing a variable:

var myDistance = getDistance(10, 5);

When the getDistance function gets called, it gets evaluated and returns a numerical value that then becomes assigned to the myDistance variable. That's all there is to it.

Exiting the Function Early

Once our function hits the return keyword, it stops everything it is doing at that point, returns whatever value you specified to the caller, and exits:

function getDistance(speed, time) {
	var distance = speed * time;
	return distance;
 
	if (speed < 0) {
		distance *= -1;
	}
}

Any code that exists after our return statement will not get reached. It will be as if that code never even existed.

In practice, we will use the return statement to terminate a function after it has done what we wanted it to do. That function could return a value to the caller like you saw in the previous examples, or that function could simply just exit:

function doSomething() {
  let blah = "Something interesting";
  return;
}

Using the return keyword to return a value is optional. The return keyword can be used standalone like we see here to just exit the function. If a function does not specify anything to return, a default value of undefined is returned instead.

Function Expressions

The functions we've seen so far are of the function declaration (or statement or definition) variety. There is another common way to work with functions, and that is the function expression way. In this approach, our functions are typically unnamed and associated with a variable. This makes more sense with an example, so here we go:

const area = function(width, height) {
  return width * height;
}

alert(area(4, 5)); // displays "20"

We have a function called area, and the way we use it is just like we would any function we've seen so far. The main visual difference is in how we write the function body. Getting into specifics, what we have here is an anonymous function assigned to the variable area. As we can imagine, it is anonymous because this function has no name. It doesn't have to be that way. We can totally name the function as part of a function expression:

const area = function areaHelper(width, height) {
  return width * height;
}

alert(area(4, 5)); // still displays "20"

In this case, we still have a function assigned to the variable area. What is different is that our function has a name, and that name is areaHelper! The areaHelper name isn't exposed outside of the function body itself. This means that the only way to call this function is via the area variable. If that is the case, why would we bother naming our function? There are two reasons:

  1. Debugging our code is easier when we encounter a named function
  2. For more advanced scenarios, we may want to recursively call our function. The only way to do that is by referencing the function by name, and we'll cover recursive functions in a distant future

What makes function expressions interesting is that they open the door for some really cool techniques that we would otherwise not be able to do.

Tip: Immediately Invoked Function Expression (IIFE)

A function doesn't have to be invoked separately from when it gets defined. We can define a function that gets executed immediately, and such a function is known as an Immediately Invoked Function Epxression or IIFE for short. The way we define an IIFE is by wrapping our function expression in a bunch of extra parenthesis. Take a look at the following example:

(function() {
  let greeting = "Hello";
  alert(greeting);
})();

When this code runs, the word Hello is displayed in an alert dialog. What makes this unique is that we can't access the greeting variable at all. It is locked and kept private inside the IIFE, so this is a good way to have our code do something without having its interrnals be accessible publicly.

Conclusion

Functions are among a handful of things that you will use in almost every single JavaScript application. They provide the much-sought after ability to help make our code reusable. Whether we are creating our own functions or using the many functions that are built-in to the JavaScript language, we will simply not be able to live without them.

What we have seen so far is how functions are commonly used. There are some advanced traits that functions possess that we did not cover here. Those uses will be covered in the future...a distant future. For now, everything we've learned will take us quite far when it comes to how functions are used in the wild.

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends