3. Functions


In This Chapter

Learn how functions help you better organize and group your code

Understand how functions make your code reusable

Discover the importance of function arguments and how to use them


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

Image

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.

Image

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.

1. Frank Caliendo FTW: http://bit.ly/kirupaFrankCB.

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.

Creating a Function That Takes Arguments

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

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

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. There are differences, however, in 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. As you know, this function simply displays some text that you tell it to show (see Figure 3.3).

Image

FIGURE 3.3 The text “my argument” is displayed as a result of the alert function.

Let’s look at this a little closer. Between your opening and closing parentheses 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, within this chapter itself, another function that we briefly looked at that takes arguments is our showDistance function:

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

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

function showDistance(speed, time) {

    ...
}

Functions that don’t take arguments are easy to identify. They typically show up with empty parentheses following their name. Functions that take arguments aren’t like that. Following their name and between the parentheses, these functions will contain some information about the quantity of arguments they need, along with some hints about what values your arguments will take.

For showDistance, you can infer that this function takes two arguments: the first corresponds to the speed and the second 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 the function inside the parentheses.

showDistance(10, 5);

Functions that take arguments, however, contain some information about the quantity of arguments they need in the parentheses following their name, along with some hints about what values your arguments will take. To emphasize this, let’s look at Figure 3.4.

Image

FIGURE 3.4 Order matters.

When the showDistance function gets called, the 10 corresponds to the speed argument, and the 5 corresponds to the distance argument. That mapping 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 (see Figure 3.5).

Image

FIGURE 3.5 The names of the arguments are treated as variable names.

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


Image Note

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.


In general, to make the code you are writing clear, just provide the required number of arguments for the function you are calling. Don’t complicate things unnecessarily.

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:

var myDistance = showDistance(10, 5);

The myDistance variable will store the results of the calculation done by the showDistance function. There are just a few things you need to know about being able to do something like this.

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 speed and time. Instead of displaying an alert, we 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 = showDistance(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 whatever called it, 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 be reached, such as the following highlighted lines:

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

    if (speed < 0) {
        distance *= -1;
    }
}

It will be as if that chunk of 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 exit:

function doSomething()   {
    // do something
    return;
}

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


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.220