Declarations
Function declarations, otherwise known as function statements, are one of the ways to create a function in JavaScript. You'll notice them when you see the function
keyword starting them off. Let's look at a few key rules.
Key Notes
Declarations start by stating the
function
keyword.Next, the function gets a name. It can be anything and should be camel cased.
Add empty parenthesis or parameter names in the parenthesis.
Put the defining statements inside
{}
.Will be hoisted.
File Location
We will be working in the following file:
Sample Code
The following function declaration has two parameters:
Return
Let's look at the structure of the above function, notice how it says return a + b
. Let's talk about what return
really means! From the docs, The return statement ends function execution and specifies a value to be returned to the function caller.
So what does that mean? Well let's break it down:
ends function execution: this means that this is the end of the function. Things after the return will not be run, so all code needs to be before the return in order to run.
specifies a value to be returned to the function caller: this is what you'll get back from the function, so when you run a function, if you expect it to give you something, that's what return does. So in the above example it is returning the value of a + b.
So, whatever is returned in the function is all that you will get from it. In the above example, if you wanted a - b
, you would have to return that instead, because all you're going to get from it is a + b
.
Calling the Functions
Here we'll 'call' the function two different times:
Hoisting
Function declarations will be hoisted in JavaScript. This means that the call can come before the function is declared.
Practice
Practice writing 3 different function declarations. You can come up with your own concepts or you can follow our criteria:
Write a function with two parameters(a, b). The function should subtract number b from number a and return the value. You should also log the value to the console.
Write a function with two parameters(first, last). The function should take the two parameters and say hello to a user by their full name. For instance, "Hello, Kenn Pascascio".
Write a function that has one parameter(minutesLeft). The message should print, "You have 5 minutes left in the show."
Last updated