Modul 3 von 16 · Medien
The Return keyword
The return keyword and function scope
Return is a reserved JS keyword that is used only by functions in order to expose a result to the open world!
What does this mean?
Take a look at the function above. Normally you may expect that after line 5 you can console.log the a and b variables in order to see the values. If you do this though you will get an error. That is because these variables have been created inside the function, thus they are available ONLY inside the function's body! This is happening due to var keyword, and it's scope (range of usage and access). Var keyword it's what we call function scope, that means lives inside the function that it was born, and it will die there.
Ok. But then what if we want to have access to the result of these variables outside the function? Then the return keyword comes to the rescue!
Return is what this function returns (or gives back). In other words the result of the function. We can have access to this result by assigning the function's invocation (we call it the function) into a variable.
Attention: That doesn't mean that the other lines of code inside the function will not be executed. Everything will be executed normally from top to bottom as always, anytime the function is invoked (called). Whatever we put in the return we can access it and assign it to a variable outside the function though.
On the example above, in line 7 we store the number 30 (a + b) to the resultSummary variable. Then the resultSummary is equal to WHATEVER the summary function returns!!!
Last but not least, once the return keyword is reached inside the function, the function exits immediately and returns the value that follows the keyword. In other words if we write some code after a return keyword, this code will never be executed.
Every function can have only one return keyword on the same block.