Is it Required to have a Return Value in JavaScript Function ?
In this article, we are going to resolve the query of whether or not it is mandatory to use a return statement in a JavaScript function.
Example: Look at this simple JavaScript function that uses a return statement and works just like a function in any other language.
Javascript
function add_and_multiply(a, b) { return ((a+b) + (a*b)); } let sol = add_and_multiply(5, 10); console.log(sol); |
65
But what would happen if we do not use a return statement inside this function?
JavaScript function without a return statement: In JavaScript, using a return statement inside a function is not mandatory. You can choose to drop it if needed and the program will still run fine. Let us look at some examples to see how it works.
Example 1: The code below is the same as the previous one, except that we have removed the return statement from inside the function add_and_multiply.
Javascript
function add_and_multiply(a, b) { // Removed the return statement } let sol = add_and_multiply(5, 10); console.log(sol); |
undefined
You can see that this time, although there is no return statement, we still do not get an error but rather, get this term ‘undefined’ printed on the screen. This is what happens when you try to leave the return statement in a JavaScript function.
Example 2: In the above example, although the output is not desirable, still, it is better than an error. However, there is a fix for this as well.
Note: In the example, we remove the variable sol while calling the function. We also added an expression for calculation inside the function. But still, we neither get an error nor any other output. Note that we have added this expression inside the function to simply show that no matter what the function has inside of it, no output will be returned if the return statement is not present. You can skip adding this expression and you will still get the same output.
Javascript
function add_and_multiply(a, b) { // Added an expression here var ans = ((a + b) + (a * b)); } // Removed the variable sol add_and_multiply(5, 10); console.log(sol); |
Output:
Nothing is printed except this!
Example 3: A better way to work around this situation would be to simply add a print statement inside the function to print the result of the calculation. That way, the function will perform something useful and we will still not need to use the return statement.
Javascript
// Removed the variable sol add_and_multiply(5, 10); // console.log(sol); function add_and_multiply(a, b) { // Added an expression here var ans = ((a + b) + (a * b)); // Print the variable console.log(ans); } |
65
This is essentially how we can choose to use or drop the return statement in a JavaScript function.
Contact Us