Javascript ternary condition with only one value

Asked

Viewed 1,494 times

11

A very basic Javascript question, in a ternary condition how can I have action only in an if without the need of Else?

Example

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

If you don’t want anything to happen to Else, how would it look?

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

(!test) ?: test1(); 

1 answer

11


This is possible with the operator && as follows:

(test) && test1();

In that other answer, What is the && in between strings operator?, I show how exactly the operator works && in Javascript, and why it is possible to use it this way... in fact it is a direct equivalence: a && b => a ? b : a.

When using this in the form of a statement, the resulting value is discarded, which ends up making it look like a if without else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.