After the return statement
in a function is executed,
further execution of
the function is terminated.
Consider the following example:
In the example given above:
- 
When the calculateSumfunction is invoked,
first we get the output"Calculating...".
 
- 
Then the sum number1 +  number2is returned.
 
- 
After the return statement,
the function execution is stopped.
The statement console.log("Calculation complete")is not executed
and
hence we don't see it in the output.
 
Consider the following example:
In the example given above,
in the function getStudentFee:
- 
If the value of the nationalityproperty of the parameterstudentis not"India",
the value ofcourseFeeis returned.
 
- 
If the value of student.nationalityis"India",
a 10% discounted course fee is calculated,
stored indiscountedFee,
and
the value ofdiscountedFeeis returned.
 
We can rewrite the getStudentFee function
in the example given above,
to make use of the fact that
the return statement terminates
further execution of a function.
In the example given above,
in the function getStudentFee:
- 
If the value of student.nationalityis not"India",
we return the value ofcourseFee.
Since further execution
of the function is stopped,
we do not need to provide the else statement.
 
- 
If the value of student.nationalityis"India",return courseFee;will not be executed
and
we move to the next statement.
A 10% discounted course fee is calculated,
stored indiscountedFee,
and
the value ofdiscountedFeeis returned.
 
So far, we have mainly used
the return statement to
return a value from a function.
The return statement can also be used
to purely stop further execution of a function.
In the example given above,
in the displayGreeting function:
- 
If the value of user.nameis falsy,
thereturn;statement is executed.
This returnsundefinedand
stops further execution of the function.
 
- 
If the value of user.nameis truthy,
thereturn;statement is not executed
and
we get an output from theconsole.logstatement.
 
In the example given above,
the return statement
does not return any value.
It's purpose is purely for
terminating further execution
of the function.
In the example given above,
the if statement -
if (!user.name) return;
is known as a guard clause.
A guard clause prevents
further execution of a function,
for a certain condition.