95

I stumbled across some javascript syntax that seemed like it should produce a parse error of some kind but doesn't:

if (true, true) {console.log('splendid')} else {console.log('horrid')} // splendid
if (true, false) {console.log('splendid')} else {console.log('horrid')} // horrid

It seems only the last expression affects the logic, though all expressions are executed:

if  (console.log('super'), true) {console.log('splendid')} // super splendid

Anyone know why that is valid javascript syntax? Is there any practical use for it?

1
  • 8
    The simple answer is, "because C did". Commented Mar 18, 2011 at 16:49

7 Answers 7

91

The comma operator chains multiple expressions together, and the result of the operation is the value of the last operand. The only real use for it is when you need multiple side effects to occur, such as assignment or function calls.

Sign up to request clarification or add additional context in comments.

5 Comments

Could you please be more specific about "assignment or function calls"? What do you mean? In general everything could be written without the comma operator as well.
Some programmers wants to write a function by writing the fewest lines of code as possible. While this may be an interesting challenge, I think they often falls into unnecessary complexity making their code hard to understand / maintain.
doesn't make much sense to me that why is this allowed in the first place, If I were to rewrite the if statement written above in the question, I would simply put console.log('super') right above the if clause.
if(a = getAValue(), b = getBValue(a), c = b * π, c >= 42) { /* whoa */ }
You know those random images you see in school maths books? I just saw one with this exact kind of syntax which is why I even found this question. Amazing that I can learn JS from being curious about some random image in a maths book XD
58

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#comma_operator

2 Comments

Thanks for actually answering the question with sources.. pity I had to scroll through a bunch of other higher-rated answers to get to it
The MDN documentation must have been updated as it now says "The comma operator evaluates each of its operands (from left to right) and returns the value of the LAST operand."
21

commas in javascript are actually pretty arcane. The coolest use I have seen is this

while(doSomething(), checkIfSomethingHappened());

the most common would be the way var is used in modern js

var foo = 1,
    bar = 2;

5 Comments

That's what do Something(); while (hasSomethingHappened()) loops are made for…
I understand why it could be used in a loop statement. However, the OP question was about the if statements.
@Bergi ... do/while loops are just stupid, because you see statements before you see the condition. I actually quite like the comma operator used as in Matt's example. Ingenious. I bet I would get some raised eyebrows when I'll use it the next time round.
Brilliant example in while statement. LOVE IT. It would likely be equivalent to for(;doSomething(),checkIfSomethingHappened(););
@RobertKoritnik Well you see statements before the condition because they are executed before the condition? Also it's no different with the comma operator…
7

This is also the same as in most other programming languages where you might have multiple iterators in a loop.

int x,y;
for(x = 0, y = 0; x < 10 || y < 100; x++, y++) {
....
}

2 Comments

I understand why it could be used in a loop statement. However, the OP question was about the if statements.
ALthough in for statement it works differently, because first expression is only evaluated once while second and third are on each iteration. In if/while statement all expressions are evaluated on each visit of the statement.
2

I permits to do operations and comparisons in the same context.

Example:

if(a = 2, a > 1) console.log('a is', a)

Comments

0

It seems like if performing multiple statements, only the "last" eval result is used as the conditional.

if (true, true,  false) alert(true); else alert(false);  (false)
if (false,false, A = 1) alert(true); else alert(false);  (true)

maybe like:

if (eval('false;false;A=1')) alert(true); else alert(false);  (true)
if (eval('true ; true;A=0')) alert(true); else alert(false);  (false)

Use: I needed a case insensitive Array/Object Search. (using get/set)

A = {Apple:12.3,Pear:34.5,Peach:3.22};
if (A.find = "pear",  A.found) alert(A.key + ' = ' + A.value);  (Pear = 34.5)

1 Comment

Yes, this is explained succinctly in Ignacio's answer: the result of the operation is the value of the last operand
-1

Using the comma operator helps you to chain multiple conditions. It's not just about the if statement, you can use it in the variable definition or function calls.

I highly recommend to read this.

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.