JS inspections - assume only two states for booleans, forget "undefined"

8243 says that JavaScript statement "( someVariable || false ) " may be simplified to just "someVariable" but it ignores the fact that in JavaScript boolean variables have 3 states - true, false and undefined ! So the statement above means if "someVariable" is undefined then it's false and it's not the same as just leaving it undefined - sometimes an exact boolean variable is required.

5 comments
Comment actions Permalink

For example, I saw people making the following JS mistake - if ( someMethod()){ form.submit() } meaning not to submit the form if "false" is returned. But the form was also not submitted if nothing (i.e undefined) was returned, which wasn't the original intent. So in this case "false" and "undefined" are two different things - "undefined" here meant actually "true" :)

The fact that JS booleans have 3 states is, of course, unusual.

Edited by: Evgeny Goldin on Mar 25, 2008 12:18 PM

Edited by: Evgeny Goldin on Mar 25, 2008 12:19 PM

0
Comment actions Permalink

In boolean expressions, undefined is considered false (as are empty strings and zero valued numbers). If you really want to test a boolean value for false only, and not undefined, use the identity equality operator (===).

0
Comment actions Permalink

Yes, I know that :)

My point was that IDEA inspections assume only two states for boolean variables - either "true" or "false". And then statements like "( someVar || false )" are highlighted as warnings, ignoring the fact that "someVar" may be undefined and this statement just made it explicit "false".

0
Comment actions Permalink

Ok, hope it'll be fixed.

0

Please sign in to leave a comment.