Return statement

In JavaScript, the return statement is used to specify the value that a function should return.

So, if we calculate the sum of two numbers, we can return the result, save it in a variable, and use it later:

Loading Code . . .

In the example above, the area function returns the result of the multiplication of the width and height parameters. The return statement is used to return the result of the function.

The return statement can be used to return any type of value, including strings, numbers, objects, and arrays.

Then, we can save the result of the function in a variable and use it later. In the example above, we save the result of the area function in the mySquareArea variable and use it to print the result in the console.

For sure, you can execute the function without saving the result in a variable:

Loading Code . . .

Stop the execution of a function

The return statement can also be used to stop the execution of a function. If the return statement is executed, the function will stop executing.

Loading Code . . .

In the example above, the area function checks if the width or height parameters are less than zero. If they are, the function returns a message and finishes the function execution.

In other words, the return in the last line of the function is not executed if the if statement is true.


Challenge time!

In this challenge, you will create a function called isEven that takes a number as an argument and returns true if the number is even and false if it is not.

Loading...

© 2024 - ®Mewters