This course has been updated! We now recommend you take the Getting Started with JavaScript, v2 course.

Check out a free preview of the full Introduction to JavaScript Programming course:
The "Functions" Lesson is part of the full, Introduction to JavaScript Programming course featured in this preview video. Here's what you'd learn in this lesson:

Functions allow you to create a block of code that can be called at anytime. Functions can also take parameters as input enabling the block of code to run more dynamically. Kyle creates a few different functions and show how to pass parameters and return values.

Get Unlimited Access Now

Transcript from the "Functions" Lesson

[00:00:00]
>> Kyle Simpson: A function is a way to logically group a piece of code together, kinda like a block is. But a function also makes that block of code something that you can call more than once. So it's kind of like a loop, and it's kind of like a block.

[00:00:15] But it's not gonna run forever like a loop does, and its not gonna run only once right now like a regular block does. So it's kind of a third different concept here. It's like putting a set of stuff into this special location and being able to say as many times as I need it, I can just call out to that stuff and it will run.

[00:00:36] I might need it once. I might need it five times. I might need to do it over and over and over again. It doesn't really matter. We use the function to sort of logically group a set of tasks together. So I have kind of a silly running example in the book.

[00:00:52] If you've read any of the book, I have the silly example of the phone store, or you're purchasing a phone, or whatever. So if you haven't read it, then you can go back and understand what I'm talking about. But here, in this running silly example I have, the phone store employee doesn't want to calculate all of the taxes for your final purchase amount.

[00:01:10] When you're talking to her and you're saying I wanna buy this phone and this accessory or whatever, she doesn't wanna redo that on her calculator every time. That's a set of tasks that's repetitive that's going to need to happen for pretty much every customer that buys something. And so, there's almost certainly a program that does that for her to check out programs.

[00:01:32] She can swipe your credit card, it automatically calculates how much to charge and all of that. And that's conceptually the same thing as a function. It's taking a specific set of tasks and putting it into a thing that I can repeat on demand. Whenever I want it, I can just invoke it, and say do that set of things, and it will just happen, okay?

[00:01:51] So [COUGH] the example that we see here is I have a variable that I'm declaring with the value 99.99. That's the price of a phone. And I wanna print the amount. I could've put a console.log statement here, right? I could've said console.log amount, and it would've printed it.

[00:02:09] And then, I said amount equals amount times 2, which doubles the value. And then, I could've put another console.log. But as soon as I did that twice, as soon as I typed the same thing twice into a program, I might start to ask myself why am I repeating myself?

[00:02:26]
>> Kyle Simpson: Could I take that set of statements that I repeated and put that into a location and give that location a special name, and whenever I want that stuff to happen, just call it by name? That's what a function's doing. So what is my set of statements? It's just one statement in this case.

[00:02:43] But it's slightly more complex than just calling console.log amount. You'll notice that I'm also saying to fixed. Now, to fixed is a method that's available to all numbers in JavaScript. And it essentially formats them as a string with a certain number of decimal places on it. Kind of like dollars, right?

[00:03:05] US dollars. So if I wanted to take the number 99.99, or the number 199.98, and make it into a string that absolutely had exactly two digits, then I could use the two fixed. Let me illustrate. What if I had the number
>> Kyle Simpson: 3.141519 I can't remember. That's all I remember.

[00:03:28] 1415926 or something like that, right? So that's the first several digits of pi. You'll notice I didn't win any pi digit memory contest as a kid. Okay, that's the first several digits of pi. But what if I wanted to print out that, let's assign that to some variable, so let's assign it to a.

[00:03:53] What if I wanted to print out that value, but only to two decimal places? Or let's actually say to three decimal places. Well, I could say, a.toFixed 3. And you'll notice that I'm not gonna get a number. I'm now gonna get a string, the string 3.142.
>> Kyle Simpson: So we rounded that digit.

[00:04:20] We rounded it by the fourth digit, we rounded that third digit up to 2. So tofixed is a way to get a number to a particular precision, to a particular number of decimal places. So nice and helpful. I almost always use this when I'm, the only place I hardly ever use it is for printing out dollars and cents.

[00:04:43] Cuz another observation that we could make is what if I had the variable a equals 3.5, and I wanted to print that out as dollars? Well, it's missing a zero on the end, right? If I just said console.log a
>> Kyle Simpson: And I only get 3.5, which isn't as friendly for US dollars.

[00:05:05] So if I said console log A dot two fixed, and I said give me two decimal places. You notice I get 3.50.
>> Kyle Simpson: That's how I typically use it is I use it to format US dollars. [COUGH] But that printAmount function is a utility that I can repeat multiple times.

[00:05:28] And imagine how much more useful it would be if instead of just one statement, if I had three or four or ten or 20 or 100 statements that were logicallconnected together. If it took five different things to do to print out my amount, I would put all five on those in a function, and then I would only be repeating the function call rather than repeating all of its contents over and over again.

[00:05:54] So that's our primary benefit to a function is being able to take a block of statements and collect it together into a repeatable sort of named label, if you will. So a little 60-second homework. Declare yourself a function. Put a couple of statements in it, whatever statements you want, like assignment statements or whatever.

[00:06:18] And repeat it a couple of times in your console.
>> Kyle Simpson: You might have called your function foo, like I'm the habit of doing. And that might take a is equal to a times 2. And a is equal to a plus 3. So we're gonna multiply it by 2, and then add 3 to it.

[00:06:41] Those are my two statements. Now, If I start off with an a is equal to 10, and I call foo once. And then I console.log(a). What would I be expecting the output of this to be? Hopefully, you're awake enough to do some basic math here. A [COUGH] starts out as 10, all right?

[00:07:03] The first time I call foo, it's going to say that 10 times 2. So now, a is going to be 20. And then, we're gonna add 3 to it. So now, a is gonna be equal to 23. So we'd expect it to print out the value 23. Now, if I call foo two more times, and then I print out a again.

[00:07:24] I'll spare you the mental acrobatics. Let's just run it and let's see what happens.
>> Kyle Simpson: So we know this one's gonna print out 23. This next one, what's it gonna print out?
>> Kyle Simpson: So it was 23 times 2, which was 46, plus 3 was 49. And then, 49 times 2 is 98, plus 3 is 101.

[00:07:55] Question?
>> Kyle Simpson: Question was about putting our functions before our variables. Did it matter if I did that or I did that? No difference to JavaScript. It goes back to that topic that we kind of skirted by earlier, the topic of hoisting, the topic of lexical scope. Scope enclosures, book covers it in-depth.

[00:08:21] The Advanced JavaScript training covers, and in depth. But for our purposes, you can put declarations in any place in your program. I typically put all of my declarations at the top of my programs. I put all my functions at the top, and then I put all my variables.

[00:08:36] That's my preferred style. But as long as all your variables are at the top, you won't have any surprises. I mean, as long as all your declarations are at the top, you won't have any surprises.
>> Speaker 2: If you consistently do that it makes it easier to maintain the program later.

[00:08:49]
>> Kyle Simpson: That's generally a good rule to have a consistent style, whatever it is. If your style is to put your functions at the bottom and your variables at the top, that's fine. But it's a good idea to always be consistent with that in your program.
>> Kyle Simpson: Okay, now, functions can also receive what are called parameters.

[00:09:13] So here, you notice I didn't receive any parameter, but what if I received a parameter. If I had a parameter called b, that becomes a variable that's accessible to me inside of the function. So I could take this value, right here. And instead of it being the literal value 3, I could have it be the variable b.

[00:09:34]
>> Kyle Simpson: So when I run this function now, its behavior is partially dependent on what value I pass in. Does everybody see that? If I pass in a different value of b, I get a different result out. Let's try it. If I start out with a equals 10, and I say foo(3), and then I say console.log(a), what are we expecting?

[00:10:00]
>> Kyle Simpson: Same thing as before. We'd expect 23, right? a went from 10 to 20, and then we added 3 to it and it became 23. But what happens if I put in 100 here?
>> Kyle Simpson: Now we're expecting 120. Does everybody see that? So what I pass into my function changes its behavior because there's a parameter that I'm passing in.

[00:10:27] By the way, a little nuance. It's not a big deal, but terminology. I mean, I think if you're learning things it's important to learn correct terminology. When we call the function here, we are passing in what's called an argument.
>> Kyle Simpson: So you can have one or more arguments that you pass into a function.

[00:10:46] But when we declare the function, and we have these names like I can say b, and bar, and zaz, and whatever. These variables here are called parameters. So in other words, there's a match, a one to one match, between an argument that gets passed in and the parameter in that position.

[00:11:08] A lot of people use arguments and parameters interchangeably as meaning the same thing, because they get assigned to each other so it seems like they could be considered the same thing. To be completely specific on terminology, it's an argument when you pass it in, it's a parameter when you declare it.

[00:11:31] So this parameter b that we've got, got assigned the argument 100. And then, we use that parameter as a variable, and we've printed it out. So let's try this again. If i said foo(5) and foo(25) and foo(100). So I called foo three different times with three different variables, all accumulating my results into this a.

[00:11:57] What's my end result gonna be?
>> Kyle Simpson: Oops.
>> Kyle Simpson: My end result
>> Kyle Simpson: The suspense is killing me.
>> Kyle Simpson: 250.
>> Kyle Simpson: Is there a question?
>> Speaker 3: Asking about passing a function as a parameter of another function.
>> Kyle Simpson: So yes, you can. And then, the next answer that was given might be slightly misleading.

[00:12:30] So let me just quickly divert into that.
>> Kyle Simpson: If I called foo, let's say I had two different functions here.
>> Kyle Simpson: And it doesn't matter what's in bar right now. If I said foo, and I gave it the name bar. I passed in bar. What I'm doing is getting the value that is currently in bar.

[00:12:54] What is the value that's currently in bar?
>> Kyle Simpson: It's a function. It's a function value. So I'm passing the function as an argument, and it's getting assigned to the parameter b. So if I said plus b here, what is b? b's a function, which, that's not really what we want.

[00:13:14] We wanted the thing to be called. I could call it here, and whatever it returned, I'd get that value. But if you pass a function as a value, it's just a function. If you call it,
>> Kyle Simpson: Then what it returns is what gets passed in as the argument.

[00:13:32] So there's the difference between passing a function, and passing the result of a function call.
>> Kyle Simpson: So hopefully that clears up the questions that were being asked in the chat room.
>> Kyle Simpson: Okay.
>> Kyle Simpson: One last detail on those functions. Let me back up. One last detail on those functions.

[00:14:00] These functions can return values as well. They can pass in values, they can return values. So if I said return a divided by 2.
>> Kyle Simpson: If I say var a equals 10, and I call foo with 3, we know a is going to become what?
>> Kyle Simpson: It's 23, right?

[00:14:28] But what if we took that return value and assigned it to another variable? You see, when I invoke foo, it's going to run. But then, it's gonna return me a different value. In this case, it's gonna compute 23 divided by 2. Which is?
>> Kyle Simpson: 11.5. [LAUGH] So 11.5 is the thing that's gonna come back and get assigned into the variable b.

[00:14:57] So if I say console.log(b), I'm expecting to get 11.5. So if we take that program and put it into our console.
>> Kyle Simpson: We're expecting both 23 and 11.5 to be printed out. And in fact, that's what we get.