You will learn how to write the return statement in JavaScript. The return statement is used to stop the function’s execution and return to the function caller.
Whether you’re writing simple utilities or complex applications, mastering the use of return is important to your ability to write clean, efficient, and reusable code. It allows functions to return results you can use elsewhere in your program.
Syntax :
return expression;
Here, expression is the value or operation that will return the function. If no expression is used after the return statement then it will return undefined.
Most functions contain internal computations or procedures; return statements are how to obtain the function’s result. If not, the function will exist without contributing anything of value to the logic of the program.
For a better understanding of how to use return statements, we will understand with the help of example,
function checkEvenOrOdd(num){ if (num%2 == 0){ return 'Even'; } return 'Odd'; } console.log(checkEvenOrOdd(9)); console.log(checkEvenOrOdd(2));
Output for the above code is :
Odd Even
We can now clearly understand how to utilize return statements in JavaScript.
The return statement is the premise for writing effective and reusable functions in JavaScript. Knowing its syntax and an example will enable developers to write cleaner more efficient code.