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;
Share:
18,188
Emerceen
Author by

Emerceen

Updated on June 29, 2022

Comments

  • Emerceen
    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ş
    Ceylan Mumun Kocabaş over 7 years
    is it right to pass just null for the false block, when we use the ternary?
  • taguenizy
    taguenizy over 7 years
    You could. I wouldn't use it. I use ternary when I know I have 2 operations. If just care about the true or false condition I would use it this way. It's more a preference then anything @CeylanMumunKocabaş
  • taguenizy
    taguenizy over 7 years
    Edited @RobG. Thanks for the correction ;)
  • RobG
    RobG over 7 years
    @CeylanMumunKocabaş—you can do that, but it's more to type and not as clear as using a simple if.