Javascript one line If, only state true
18,188
Solution 1
if(variable) block;
With the conditional operator you need the false bit also.
Solution 2
You can do:
variable && block
For example:
let variable = true;
let o = variable && 3;
Author by
Emerceen
Updated on June 29, 2022Comments
-
Emerceen almost 2 years
In default 'if' one line statement are two block, for true, and false:
variable ? true block : false block;
How declare 'if' with one block?
I expect something like this:
variable ? true block;
-
Ceylan Mumun Kocabaş over 7 yearsis it right to pass just
null
for the false block, when we use the ternary? -
taguenizy over 7 yearsYou could. I wouldn't use it. I use ternary when I know I have 2 operations. If just care about the
true
orfalse
condition I would use it this way. It's more a preference then anything @CeylanMumunKocabaş -
taguenizy over 7 yearsEdited @RobG. Thanks for the correction ;)
-
RobG over 7 years@CeylanMumunKocabaş—you can do that, but it's more to type and not as clear as using a simple if.