4 ms·
I never really got the reason for doing this var condn = ...; if (condn) { return true; } return false;
by devxpy 7y ago
I never really got the reason for doing this
var condn = ...;
if (condn) {
return true;
}
return false;
- deleted 7y ago[deleted]
- bberrry 7y agoBecause it gives you the opportunity to descriptively name the expression, sparing others from parsing it mentally.
- Liron 7y agoDo you also think `if ((x > 3) == true)` is more descriptive than `if (x > 3)`?
- sombremesa 7y agoCan't the returning function be named appropriately?
- bberrry 7y agoI mean, it's the same thing as extracting the boolean expression into a function and calling that in the if statement. It's also easy to imagine a quite long expression that would benefit from breaking into two or three descriptive names. It's a good tool for your own sake when coding, to not get the logic tangled up.
- pdkl95 7y agoStoring the result of a Boolean expression isn't the strange part. Storing it in a well-named variable can make the code a lot easier to read; the name (hopefully) communicates intent, and it can separate a conditional action into separate steps. The strange part is testing Boolean value... to return the same value as Boolean constants. Why wasn't the Boolean result simply returned directly? var condn = ...; return condn; The if statement isn't necessary. Even if you wanted to explicitly return only "true" or "false" - using the if statement to convert truthy and falsy results into true booleans - using double not operators removes q potentially mispredicted branch. var condn = ...; return !!condn;
- bberrry 7y agoAh, sorry, I completely failed to realize that was the question being asked. :)
- tuyiown 7y agoIt's been discussed here before, I don't buy the descriptive argument per se, it's the function name purpose, but another argument is to anticipate further processing then condition description can become purposeful, and you just have to add code in the right branch
- TuringNYC 7y agoPerhaps you need to log the value of “condition” twice (once in each of 2+ cases) and you don’t wish to evaluate condition twice.
- mjw1007 7y agoOne reason is that a code-coverage checker will tell you whether you're testing both cases.
- roel_v 7y agoMaybe there once was a breakpoint at the return false, or an assert, and it was just left like this in case the breakpoint is needed again.
- indentit 7y agoModern debuggers generally support conditional breakpoints, but they often incur a high performance penalty, so this reasoning makes sense to me.