Search code examples
javascriptif-statementshort-circuiting

New way to write the if statement


I found a way to write the if statement in another way (I think) while searching in the source code of a website.

Instead of:

if(a)b;

or:

a?b:'';

I read:

!a||b;

Is the third way the same as the first two? And if yes, why we would use the third way?


Solution

  • The third way is the same as the previous ones. One argument to use it is saving bytes. A strong argument against using it is readability. You'd better focus on readability in writing code, and use a minimizer (such as Google Closure Compiler) to save bytes.

    It can be even shorter:

    a && b;
    /*  !a||b  means:
     (not a) OR b
        which is equivalent to
     a AND b
        which turns out to be
     a && b
    */