Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
wwaawaw Avatar asked Sep 30 '12 19:09

wwaawaw


1 Answers

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.

like image 97
Daniel Li Avatar answered Oct 19 '22 10:10

Daniel Li