Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 624
Ross Avatar asked Aug 25 '11 20:08

Ross


2 Answers

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).

like image 104
David Titarenco Avatar answered Nov 14 '22 03:11

David Titarenco


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");
like image 37
Guffa Avatar answered Nov 14 '22 04:11

Guffa