Just bumped into the fact that an if
statement can have multiple parameters in javascript:
// Webkit
if (true, true, false) console.log("this won't get logged");
How well is this supported?
p.s. I get that this is similar to using &&
, but this is interesting and a google couldn't provide the answer.
If statements can't have "multiple parameters". What you observed is the use of the comma operator.
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
Now we see why (true, true, false)
doesn't log anything whereas (true, false, true)
will. As a side note, this syntax is ubiquitously supported (but should almost never be used).
That is not a feature of the if
statement, it's the ,
operator.
You can separate expressions with a comma, and each expression will be evaluated but only the last one is used as value of the whole expressions.
In your example it's pretty useless, but sometimes you want an expression evaluated for it's side effects. Example:
var i = 1;
if (i += 2, i == 3) console.log("this will get logged");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With