Is <boolean expression> && statement() the same as if(<boolean expression>) statement()?

Are the two identical?

Suppose you have:

var x = true;

And then you have one of either:

x && doSomething();

or

if(x) doSomething();

Is there any differene whatsoever between the two syntaxes? Did I stumble across a nice bit of sugar?


Solution 1:

Strictly speaking, they will produce the same results, but if you use the former case as a condition for something else, you will get dissimilar results. This is because in the case of x && doSomething(), doSomething() will return a value to signify its success.

Solution 2:

No, they are not identical. While if is a statement, the AND operator is an expression.

That means you could use its result in an other expression, which you can't with an if-statement:

var result = x && doSomething();

Yet, in your case both have the same effect. Use the one that is more readable and represents your program structure better; I'd recommend the if-statement.

Solution 3:

Short answer: No.

Long answer:

A stated by @Steve x && doSomething() is an expression,

whereas if(x) doSomething(); is a statement,

As suggested by @Daniel Li and @Bergi, think:

  • an expression is computed ( supposed to return a value here ).

  • a statement is declared ( not supposed to return a value here, think side-effects ).

Why is it confusing?

  • JS allows us to write ( thatExpression );
  • JS allows us to write thatExpression;

both assuming some kind of doNothingWithValueOf statement.

How to choose?

Do you use:

  • doSomething() as an
    • expression , think IsMyObjectWhatever() or MyObjectComputedValue(),
    • or as a statement, think ModifyMyObject()

And then: Do you use x && doSomething() as an expression ?

You'll end up thinking something like thisStatement( thatExpression ); everywhere, think:

  • () expression,
  • ; statement.

Then why should I choose?

  • Obvious is that "It works." doesn´t stand for "It´s right".

  • If less obvious is when it will make the difference:

    • just think ()(()())()(); can be right, (;) is wrong.
    • check @wwaawaw Javascript: difference between a statement and an expression?
    • or expressions-vs-statements post by Axel Rauschmayer