Hi everyone,
why should I use if / else statements instead of using “return” within my execution-block of the if-statement? It appears to me to have the same effect with less code.
Example
Hi everyone,
why should I use if / else statements instead of using “return” within my execution-block of the if-statement? It appears to me to have the same effect with less code.
Example
…should have added the examples
so…what is the difference between these two:
function testElse(val) {
var result = “”;
if (val > 5) {
result = “Bigger than 5”;
}else{
result = “5 or Smaller”;
}
return result;
}
console.log(testElse(4)); // result is “5 or Smaller”
function testWithoutElse(val) {
var result = “”;
if (val > 5) {
return result = “Bigger than 5”;
}
return result = “5 or Smaller”;
}
console.log(testWithoutElse(4)); // result is “5 or Smaller”
It’s situational.
“return” will cause you to leave a function., and perhaps you have more code you want to execute within that function.
function blah(){
if (condition){
// execute line 1
// execute line 2
// execute line 3
}
else {
// execute line 4
// execute line 5
}
// execute line 7
// execute line 8
}
If you used returns in this situation:
Lines 1,2,3 would have to be squeezed into anonymous function and then returned
Lines 4,5 would have to be squeezed into anonymous function and then returned
You would never get to lines 7 & 8.
You don’t need the variable assignment there if you are returning it, just like this is enough and improve readibilty:
if (val > 5) {
return "Bigger than 5";
}
return "5 or Smaller";
can you provide a simple REAL example?
Thanks a lot.
I know …since I copy / pasted it from above example where the variable “result” was necessary I just left it in.