Why does javascript accept commas in if statements

2019-01-08 11:25发布

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?

4条回答
成全新的幸福
2楼-- · 2019-01-08 11:48

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;
查看更多
神经病院院长
3楼-- · 2019-01-08 11:51

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.

查看更多
仙女界的扛把子
4楼-- · 2019-01-08 11:53

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++) {
....
}
查看更多
登录 后发表回答