Sample Video Frame
11: Functions
You will now learn about the concept of a function. This concept can get very complex in JavaScript, but I'm going to start you off with two simple versions of the function, and then have you drill them until you get them. It's very important that you read this exercise and then watch the video to see functions in action. Functions are about movement inside code, and the best way to see things move is in a video.
A Short History of The Jump
To explain functions I'm first going to take you through a walk down a tiny history of computers, and at the end functions will make more sense.
GOTO
When you run your JavaScript code it starts at the first line and goes to the last line. The computer just takes each line, processes it, and then moves to the next one. This isn't very useful though because the power of a computer comes from doing two more things:
- Making decisions, also called "branches".
- Repeating some piece of code over and over, also called "a loop".
In the old days there was a language called BASIC, and it had this thing called a GOTO:
10 PRINT "HELLO!"
20 GOTO 10
I'm so old that this was my first programming language. You can probably read this code though and figure out what it does:
- The computer reads the line 10 and prints "HELLO!"
- It reads line 20, and goes to line 10.
- This causes an infinite loop, but that's still a loop.
Inside your computer there are many more complicated commands similar to GOTO, but most of the programming languages that you will use have banished the concept of a GOTO from their syntax.
Named GOTO
However, some languages kept the GOTO concept because it is very useful in a few situations. These langauges are similar to JavaScript, and that means they don't have a line number you type. If you want to go to a part of the code, you need to give that part of the code a name. Here's an example snippet of code from C (which looks like JavaScript):
jump_to_here:
printf("HELLO!\n");
goto jump_to_here;
This does the exact same thing as the BASIC code above, except I couldn't say "goto line 5". I had to name that line with jump_to_here
and then use goto jump_to_here;
to make it work. But, the concept is the same, I tell the computer to print "HELLO", then go to jump_to_here
so it then prints it again, jumps, prints, jumps all in a tight loop until you hit CTRL-c.
The Stack
This kind of jumping works for a while, but eventually you get into trouble. At some point you have to create variables for these places you jump to, and then you have to clean up the work of these jumps. For a really long time computer programmers did this manually, keeping track of every variable, where it was used, how a jump went, whether it came back, and all manner of nasty accounting we started to call "spaghetti code". We called it that because the code just seemed to jump around like the code follows strings of spaghetti.
The solution came in the form of the "stack". The stack is a temporary place that you can put variables just for a jump, and then the jump returns when the stack is cleared off. You just put your variables into the stack, tell the computer where to jump, and the computer handles all the accounting for you. If you need to give a block of code three variables for a calculation, you might do this:
- Put each variable on the stack.
- Tell the computer to jump to the block of code, and that you pushed three variables on the stack.
- The computer does this and also remembers where you requested this so it can return.
- Your block of code runs, using these variables, and when it's done it just says "return".
- The computer cleans up your three variables from the stack and then jumps to the place it remembered in step 3.
- Once back at the location from step 3 the computer continues where it left off.
There is also a way for your blocks of jump code to tell the computer, "Hey, when you return, tell whoever called me this variable." That is how you do a "return value".
Functions
Once we have these simple things we can make functions:
- A way to jump to a new place in the code.
- A way to give this jump location a stack of variables.
- A way to return to where we came from, with a possible return value.
A function is simply a way to jump to another part of a program, take along some temporary variables, and maybe return a value to the caller. Once you jump inside a function, it is all on its own and can then call other functions without worrying about causing trouble (maybe, depending on the language).
Anonymous Functions
The final thing you need to learn in JavaScript is that you can create temporary functions that do not have a name. Most other languages require you to name every function, but JavaScript allows you to create a quick little function that is only around for a short period of time and therefore doesn't need a name. This is usually used in something named a "callback".
A callback is a more advanced concept, but for now you can think of them as a way to say "and then". You can tell JavaScript to do something like, "read this file", then using a callback you can say, "read this file AND THEN run this anonymous function callback to do something with it".
The Code
Hopefully, you studied my descriptions above and watched the video. I feel this code here is very hard to understand unless you do those two things. Once you do, I want you to use what I wrote above, and what I said in the video, to analyze this code and trace through it the way I did in the video.
// Exercise 11: Functions
const printPerson = (name, age) => {
console.log(`Hi ${name}, you are ${age} years old.`);
}
printPerson('Zed', 44);
printPerson('Fran', 100);
printPerson('Alex', 30);
printPerson('Eve', 35);
console.log('--------------- pets ----------------');
const printPet = (owner_name, owner_age, pet_name, pet_age) => {
printPerson(owner_name, owner_age);
console.log(`That person owns ${pet_name} who is ${pet_age} years old.`);
}
printPet('Zed', 44, 'Mr. Scruffles', 10);
printPet('Fran', 100, 'Crazy', 2);
printPet('Alex', 30, 'Lizzy Lizard', 1);
printPet('Eve', 35, 'Kong The Donkey', 20);
// this part is tough! brain melting! give it a try
//
console.log('------------------ callback style ----------------');
const fancyPet = (owner_name, owner_age, pet_name, pet_age, cb) => {
cb(owner_name, owner_age);
console.log(`That person owns ${pet_name} who is ${pet_age} years old.`);
}
// notice how I use a function here as the parameter cb?
fancyPet('Zed', 44, 'Mr. Scruffles', 10, (name, age) => {
console.log(`Ooooh fancy ${name} you are ${age} old.`);
});
The video has a complete visual walk-through of this code, but I'm going to list out the important points for making a function:
- You create a function by assigning a variable name, just like any other variable in your program. I use
const printPerson =
here to make the function a little harder to accidentally replace, but you could also uselet
. - You then list each parameter in parenthesis that you want to go on the stack when the function is called:
(name, age)
. - You then use the "fat arrow", which is done like this:
=>
and says "the next bit is going to be code that will be a function." - You then type code to run.If the code is one simple line then just type it, but if it's multiple lines then put the code inside
{ }
braces (curly braces). - Finally, if you want your code to return a value, then you add
return value
to it. We will use that in later exercises to do very interesting things.
What You Should See
$ node "code.js"
Hi Zed, you are 44 years old.
Hi Fran, you are 100 years old.
Hi Alex, you are 30 years old.
Hi Eve, you are 35 years old.
--------------- pets ----------------
Hi Zed, you are 44 years old.
That person owns Mr. Scruffles who is 10 years old.
Hi Fran, you are 100 years old.
That person owns Crazy who is 2 years old.
Hi Alex, you are 30 years old.
That person owns Lizzy Lizard who is 1 years old.
Hi Eve, you are 35 years old.
That person owns Kong The Donkey who is 20 years old.
------------------ callback style ----------------
Ooooh fancy Zed you are 44 old.
That person owns Mr. Scruffles who is 10 years old.
The Other/Old Style
This function style is the new modern ES6 style, which solves a lot of problems with another style of function. The only issue with this style is you will definitely find functions created in another way, so let's take a quick look at the other way to define a function:
// new style
const printPerson = (name, age) => {
console.log(`Hi ${name}, you are ${age} years old.`);
}
// other (old?) style
function printPerson(name, age) {
console.log(`Hi ${name}, you are ${age} years old.`);
}
I'm using the first function in the code example and then showing you how to do the same definition using the other style of making a function. It's not clear if the "new style" is actually new or just another style, so I recommend you learn both. In future exercises we use versions of both because of legacy JavaScript designs, or simply because that's how it's expected in that situation.
If you ever work on a project that uses the other/old style then stick to what they do. JavaScript developers will have their opinions on which is better, so just go with the flow. I use the new style because it's a consistent syntax similar to creating any other variable, is easier to use on in callbacks, and solves a few problems with the other/old style.
Learn JavaScript Today
Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.
Still Not Sure? Try the next FREE Lesson!