Javascript: if (arg1, arg2, arg3 ...) statement

Just came across the fact that the if can have several parameters in javascript:

 // Webkit if (true, true, false) console.log("this won't get logged"); 

How well is this supported?

ps I understand that this is similar to using && , but it is interesting, and Google could not provide an answer.

+8
javascript
source share
4 answers

If operators cannot have "multiple parameters". You have noticed the use of a comma .

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) does not write anything, but (true, false, true) will be. As a note, this syntax is universally supported (but almost never used).

+14
source share

This is not a sign of an if , it is a , operator.

You can separate expressions with a comma, and each expression will be evaluated, but only the last is used as a value for all expressions.

In your example, this is pretty useless, but sometimes you need the expression to evaluate its side effects. Example:

 var i = 1; if (i += 2, i == 3) console.log("this will get logged"); 
+6
source share

It is not like && (try moving false to first or second place), it has nothing to do with if , and it is about the same as function literals, i.e. it is absolutely universal. What you are facing is a comma operator inherited from C that evaluated expressions (in fact, it always takes two expressions and more conceptually leads to nesting, like a + b + c ) from left to right, and discards everything except the last result. The last result becomes the result of the whole expression.

+3
source share

It works in IE7, so I think it is well supported.

+1
source share

All Articles