Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
r~~'s answer is good, and I absolutely agree that the condition provided in the question is ridiculous and I've never seen anyone suggest it as a generic replacement for if(var). But I think the ac...
Answer
#1: Initial revision
r~~'s answer is good, and I absolutely agree that the condition provided in the question is ridiculous and I've never seen anyone suggest it as a generic replacement for `if(var)`. But I think the actual advice that is being communicated (perhaps poorly) which is not explicitly called out in r~~'s answer is simply: "**Avoid relying on [truthiness](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).**" Or, more generally, ad-hoc implicit conversions. This rule means that any boolean test should only be performed on booleans. By this rule, `if(var)` is completely fine *so long as you know `var` is a boolean value*. This rule suggests that you should almost never use `==` and should instead prefer `===` (similarly for `!=` and `!==`). This rule implies that `null` and `undefined` should be treated as distinct values from `true` and `false` and should be tested for more explicitly. Something like this is presumably part of what led to the condition you posted, though this rule does not imply that particular condition (and that condition is unnecessarily complicated anyway). This rule definitely rules out broken, old-school patterns like `someVar = someParam || SOME_DEFAULT` intended to set `someVar` to a default value, `SOME_DEFAULT`, if `someParam` is not set. Practically, it's *very* easy for some value you expect to (only) be a boolean to actually allow non-boolean values, particularly `null` and `undefined`. To that end, I highly recommend using TypeScript^[Or, at least, some other JavaScript type checking approach, though TypeScript is the one I'd recommend and seems to have "won".] with the strictest settings possible. While TypeScript does allow you to rely on truthiness (though you can use `tslint`'s [`strict-boolean-expressions`](https://palantir.github.io/tslint/rules/strict-boolean-expressions/) to warn about this), if you declare a variable as having type `boolean`, it will catch the very many ways such variables could fail to be bound to `boolean` values. In other words, this is an effective way of actually knowing whether some variable is a boolean value. My post doesn't justify this rule, but the posts you link and many, many others illustrate the unintuitive behavior and mistakes using truthiness leads to.