Coworker had me grep for the string "true : false" through our project, and I found a lot of ternary operators returning explicit true or false. For example:
return this.state == Cursor.CLOSED ? true : false;
Not just in our project, but plenty of modules/libraries do this. It seems redundant to me, since the author could have just written it like this:
return this.state == Cursor.CLOSED;
Is it defensive coding against some gotcha in Javascript? Or just to be explicit with what you are returning?
Do_This_and_This : return true; } //Error: Expected an operand: but found return false or true. } As per understanding return false will return back to function and breaks the loop and return true will work as continue which moves to next iteration.
The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.
The ternary operator consists of a condition that evaluates to either true or false , plus a value that is returned if the condition is true and another value that is returned if the condition is false .
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically.
Is it defensive coding against some gotcha in Javascript?
No. ==
does always return a boolean value.
The conditional is completely redundant, and considered a bad practise. Simplify it!
It's quite unnecessary, but it's a pretty common mistake† in many languages. Because the equality operator is used almost exclusively in conditions, some less-knowledgeable programmers don't know and more experienced programmers occasionally forget that it can actually be used for its value. There has never been any major JavaScript implementation that had a quirk that made this necessary.
† "Mistake" feels unkind here, since the code is correct, just needlessly verbose. But I think you know what I mean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With