JavaScript ternary condition with only one value


A fairly basic JavaScript question, on a ternary condition how can I do to take action only on an if without the need of the else?


(test) ? test1() : test2();

If you do not want anything to happen at Else, how would you look?

I tried, do as in PHP more did not work:

(!test) ?: test1(); 
asked by anonymous 06.05.2014 / 19:45

1 answer


This is possible with the && operator as follows:

(test) && test1();

In this other response, What it means the & & in between strings? ", I show how exactly the && function works in JavaScript, and why it's possible to use it this way ... it's actually a direct equivalence: a && b = > a ? b : a .

When you use this in the form of a statement, the resulting value is discarded, which makes it look like if without else .

06.05.2014 / 19:47