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 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 (Figure 3.1).
If you remember from school, the distance is calculated by multiplying the speed something has traveled by how long it took (Figure 3.2).
The JavaScript version of that will sort of 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; let 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 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!
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 get familiar with them and learn all about how well they work.
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 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 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 as in Figure 3.3.
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, ( )
as in Figure 3.4.
Rounding out our function declaration are the opening and closing brackets that enclose any statements that we may have inside (Figure 3.5).
The final thing is the contents of our function—the statements that make our function actually functional (Figure 3.6).
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 (Figure 3.7).
The function call is typically the name of 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. In the next couple of sections, we are going to build on what we’ve just learned and look at increasingly more realistic examples of functions.
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 display shown in Figure 3.8.
The argument is the stuff between your opening and closing parentheses 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 chapter 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 now 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 (Figure 3.9).
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 in which you specify your arguments matters.
Let’s look at all of this in greater detail starting with the diagram in Figure 3.10.
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 as shown in Figure 3.11.
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 clearer, you should provide the required number of arguments for the function you are calling.
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 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 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) { let 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:
let 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.
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) { let 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 foo = "Nothing 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.
The Absolute Minimum
Functions are among a handful of things that you will use in almost every single JavaScript application. They provide the much sought-after capability to help make your code reusable. Whether you are creating your own functions or using the many functions that are built into the JavaScript language, you will simply not be able to live without them.
What you have seen so far are examples of 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 understanding how functions are used in the real world.
If you have any questions on the content here, don’t fret! Post on the forums at https://forum.kirupa.com for quick help from both me as well as some of the web’s smartest developers.
18.226.28.197