Functions - Return values
Learning Objectives
- Understand what is meant by the term return value of a function
- Understand how to set the evaluation value of a function call expression
Function return values
When we call a function, the evaluation value of the function call expression is also called the return value.
For example when we call 'Hello'.toUpperCase()
, the return value of the toUpperCase
is a string 'HELLO'
. We could also say that the function returns a string 'HELLO'
.
When we have written our own functions so far, we have always seen them evaluating to undefined
when we call them - they always return undefined
.
In this lesson we will look at why that is, and how we can control the return value of our functions.
We will try to write a function that triples a number. The function will be called with a number as an argument, and the function will return that number multiplied by three.
The result will look like this:
Let's start by defining an empty function:
When we call the function, the evaluation value is undefined
:
The next step would be to add in a parameter to the function, and multiply its value by 3.
But when we call the function, we still get undefined
:
If we try to console.log
the number * 3
statement, we can see that JavaScript is executing the expression and performing the calculation.
The first function call prints 15
but evaluates to undefined
. The second function call prints 6
but evaluates to undefined
.
We need a way to get that calculated value out of the function!
To do this, we can use the return
keyword:
Now our function works as we want it to!
To get a value out of a function, you must use the return
keyword. If a function doesn't have a return statement, it will always return undefined.
However, in some cases you might not be interested in the return value of a function, and that's fine. For example with console.log
we use it to print a message to a screen, not to calculate a new value. In these cases, no return statement is needed.
Early returns
An interesting feature of the return
keyword in JavaScript is that it will stop the execution of your function immediately.
Look at the following example:
The code in this function contains 3 statements for the computer to execute. But when we call the function, only two of the statements will be executed. The last statement console.log('GOODBYE');
will never happen:
This is because the function contains a return
statement before the final console.log
. Any code in a function after a return
statement will not be executed.