The code below is an example code from the basic JavaScript tutorial
“Introducing Else statements”
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
I do not understand whether the use of return statement here is correct.
I am starting to get confused on whether I need to include a return statement
even in an if statement or not, because I used to think that they are used only for functions…
I basically don’t understand when to use return statements.
It’s perfectly fine, assuming that this if/else is part of a funciton body and you want to exit the function at this point.
return statements are only used in functions, yes. They can be used in an if statement block.
The return statement is used to “exit” (or end) the function. Once a return statement is hit, no more code inside the function will run. If your function is supposed to return a value then it would be used in the way you have here (returning a string value). If you want to stop executing the function but don’t need to return a value you can use the command
return; //this returns undefined
If a function does not have a return statement, it will run until the last line of the function and then return undefined.
The example is supposed to be from inside a function. You don’t need a return statement inside of every if statement. Return statements are used to pass information outside of a function. (Edit, and to stop the execution of the function, like @ArielLeslie said)
var x = 5;
if (3 > x) {
console.log("That's impossible");
} else {
console.log("I knew this would happen");
}
In this code, there is no need to return inside of the if.
function addTwo(a, b) {
return a + b;
}
console.log(addTwo(1, 1)); // Hopefully logs 2
In this code, we need a return to get the sum of the two numbers out of the function scope.
This return result is going to void because this statement returns a string but it doesn’t assign it to a variable or a constant. Therefore, you cannot reach out this return’s result.
There is absolutely nothing wrong with returning a string or any other value without assigning that value to a variable inside of a function. I don’t understand what you’re trying to say.
I mean if you look at the given example about this problem by @kasaiy2002 doesn’t save the resulting value of return statement, so the value goes to void. i have referred to how to use return statement. I mean, while you use return statement, you must assign a variable this result of return statement.