AngularDebutant
AngularDebutant

Reputation: 1576

Simplify nested ternary in Javascript

I have the following code:

return this.condition1
        ? condition2
          ? true
          : false
        : false

Is there a way to write this without using true false?

Upvotes: 1

Views: 395

Answers (2)

Pac0
Pac0

Reputation: 23149

return this.condition1 && condition2;

should be sufficient for using in if and other conditions. Note that it's not strictly equivalent javascript to your code.

To be certain to return true or false (as the primitive boolean values), you need to coerce this as a boolean like this :

return !!(this.condition1 && condition2);

(this is really for the sake of exactitude, and I would style recommend the first simpler version in most cases, though).

Upvotes: 3

Pointy
Pointy

Reputation: 413720

Yes, you can simplify that; you don't need any ternary operators:

return this.condition1 && condition2;

Performing a test in order to choose either true or false is redundant. You can use !! to turn a "truthy" value into a boolean value, and if the test expressions already provide boolean values (such as > or < comparisons) then you've already got the values you need.

Upvotes: 7

Related Questions