Why does javascript accept commas in if statements?

JavascriptParsingLogic

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Solution 3 - Javascript

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;

Solution 4 - Javascript

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++) {
....
}

Solution 5 - Javascript

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

Example:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - JavascriptIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - JavascriptAdam AyresView Answer on Stackoverflow
Solution 3 - JavascriptMatt BriggsView Answer on Stackoverflow
Solution 4 - JavascriptSurootView Answer on Stackoverflow
Solution 5 - JavascriptvinyllView Answer on Stackoverflow