return
MDN Docs is always used for a specific task, and that's:
return;
→ break the execution returning the function as undefined
return myResult;
→ return a value.
If you're calling a function and expecting it to return
something (a String, Number, Boolean, another function call etc...)
than you might not need the if
statement (which is always more readable), instead you could use a Conditional Operator ?:
:
// EXAMPLE 1: Return a/b value using Conditional Operator
function example1( statement ) {
return statement ? "FOO" : "BAR" ;
// return "FOO"(if condition is true), else return "BAR"
// Or use undefined instead of "BAR" if you don't want to provide a return value
}
// EXAMPLE 2: Return a/b value using Array and Boolean-to-numeric conversion
function example2( statement ) {
return ["FOO","BAR"][!+statement];
}
// EXAMPLE 3: Return value or undefined
function example3( statement ) {
return ["FOO"][!+statement];
}
console.log( example1(true && true) ); // "FOO"
console.log( example1(true && false) ); // "BAR"
console.log( example2(true && true) ); // "FOO"
console.log( example2(true && false) ); // "BAR"
console.log( example3(true && true) ); // "FOO"
console.log( example3(true && false) ); // undefined
Not logical as it might seem, since you did not wrapped your return
inside an if
you cannot add more code after the appearance of return
function example1( statement ) {
return statement ? "FOO" : "BAR" ;
// Cannot put more code here
}
vs:
function example1( statement ) {
if(statement) {
return "FOO";
}
// More code here
}