Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operators returning "true : false". Why?

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?

like image 396
Ross Hettel Avatar asked Jun 12 '14 15:06

Ross Hettel


People also ask

How do ternary operators return true or false?

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.

What does ternary operator return?

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.

Does ternary operator need return?

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 .

Why ternary operator should not be used?

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.


2 Answers

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!

like image 116
Bergi Avatar answered Oct 18 '22 23:10

Bergi


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.

like image 35
Chuck Avatar answered Oct 18 '22 22:10

Chuck