Functions can be hard for a beginner to understand, but it’s a critical concept you need to get.
To make sure you understand functions completely, let’s go through what happens when you declare and use a function — this time, we’re going even slower and we’ll take things one step at a time.
Here’s the code we’re dissecting:
function add2(num) { return num + 2}
const number = add2(8)console.log(number) // 10First of all, you need to declare a function before you can use it. In the first line, JavaScript sees the function keyword and knows the function is called add2.
It skips over the code in the function at this point because the function is not used yet.
Next, JavaScript sees that you declared a variable called number. Before it can find out what value number holds, it needs to evaluate the expression on the right hand side.
The expression on the right hand side is add2(8) — so JavaScript calls the add2 function and passes an argument 8 into it.
When the argument 8 is passed into the add2 function, it gets assigned to the first parameter which is num. This means num now has a value of 8.
We’re currently inside the add2 function now.
At this point, JavaScript sees a return statement that says num + 2.
Since num + 2 is an expression, JavaScript needs to evaluate this before it can return the value. And since num is 8, JavaScript will evaluate num + 2 as 8 + 2.
So the result of the expression is 10.
Once num + 2 is evaluated, JavaScript returns the value to the expression that called the function — this means JavaScript replaces add2(8) with 10.
Finally, once the right hand side is evaluated, JavaScript creates the variable, number and assigns the value 10 to it.
This is how you read the flow of a function.
Protip: whenever you’re confused, slow down and read the flow of your program. Follow what we’ve done above. You’ll clear things up.
Exercise
Go through the flow of the function above 2-3 times. Make sure you understand how a function work. Do not proceed to the next lesson until you understand this completely.
When you’re ready, move on to the next lesson.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson