Functions in JavaScript

by kirupa   |   3 February 2014

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 your code is made up of a single statement. Most of the time, though, that will never be the case. Your code will rarely be this simple when you are using JavaScript in the real world for real-worldy things.

Getting back to our text...to highlight this, let's say we want to display the distance something has traveled:

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:

 

what the distance and speed are

 

The JavaScript version of that will sorta look as follows:

var speed = 10;
var 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 you 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:

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

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

This entire problem can be solved very easily by using what you'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 function is just to just dive right in and start using them, so let's start off by creating a very simple function. Creating a function is pretty easy. 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 your function isn't enough, though. Your function needs to actually be called, and you can do that by adding the following line afterwards:

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

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

First you see the function keyword leading things off:

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

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, you specify the actual name of the function followed by some opening and closing parentheses, ( ):

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

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

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

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

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

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:

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

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

Now, what you have just seen is a look at a very simple function. In the next couple of sections, we are going to build on what you've just learned and look at increasingly more realistic examples of functions.

Creating a Function that Takes Arguments

Like I mentioned earlier, the previous sayHello example was quite simple:

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

You 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 example:

alert("my argument");

What we have here is your alert function. You've probably seen it a few (or a few dozen) times already. What this function does is take an argument for what to actually display when it gets called:

an argument

Between your opening and closing parenthesis when calling the alert function, you specify the stuff that needs to be displayed. This stuff is more formally known as an argument. The alert function is just one of many functions 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, you can infer that this function takes two arguments. The first argument corresponds to the speed and the second argument corresponds to the time.

You 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.

showDistance(10, 5);

Because I am providing more than one argument, I 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 your function, the names you specified for the arguments are treated just like variable names:

just the function

You can use these variable names to easily reference the values stored by the arguments inside your function.

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 look 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:

var 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, you 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 your 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 your return statement will not get reached. It will be as if that code never even existed.

In practice, you will use the return statement to terminate a function after it has done what you 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() {
// do something
return;
}

Using the return keyword to return a value is optional. The return keyword can be used standalone like you see here to just exit the function.

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 your code reusable. Whether you are creating your own functions or using the many functions that are built-in to the JavaScript language, you will simply not be able to live without them.

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

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!