Home > Articles

Functions

  • Print
  • + Share This

Learn how functions in JavaScript help you better organize and group your code, make your code reusable, and the importance of function arguments and how to use them.

This chapter is from the book

So far, all of the code we’ve written contained virtually 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.

To highlight this, let’s say we want to display the distance something has traveled (see Figure 3.1).

Figure 3.1

Figure 3.1 The distance something has traveled.

If you remember from school, distance is calculated by multiplying the speed something has traveled by how long it took as shown in Figure 3.2.

Figure 3.2

Figure 3.2 The formula for calculating distance.

The JavaScript version of that will look as follows:

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

We have two variables—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. Quick note: The * character (which I threw in there without warning) between two numbers indicates that a multiplication needs to take place. Anyway, as you can see, our JavaScript 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 (as Frank Caliendo impersonating Charles Barkley would say) turrible.1 Our code is unnecessarily verbose and repetitive. As I mentioned earlier, when we looked at variables in the previous chapter, repetition makes your code harder to maintain. 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 and calories. We’ll learn all about functions, and how they do all the sweet things that they do, starting...right...now!

What Is a Function?

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

  • Groups statements together

  • Makes your code reusable

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

A Simple Function

The best way to learn about functions is 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 and only requires understanding some little syntactical quirks like using weird parentheses and brackets.

The following 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 at the end of your code block:

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

If you type all this in your favorite code editor 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 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 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 box 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 of the function you want to call (or invoke) followed again by 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 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.

  • + Share This
  • 🔖 Save To Your Account