Why does javascript accept commas in if statements?

Matt picture Matt · Mar 18, 2011 · Viewed 19.8k times · Source

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?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Mar 18, 2011

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.