Why does javascript accept commas in if statements?

后端 未结 5 1007
北荒
北荒 2020-11-29 23:47

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         


        
相关标签:
5条回答
  • 2020-11-30 00:04

    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;
    
    0 讨论(0)
  • 2020-11-30 00:15

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

    Example:

    if(a = 2, a > 1) console.log('a is', a)
    
    0 讨论(0)
  • 2020-11-30 00:21

    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++) {
    ....
    }
    
    0 讨论(0)
  • 2020-11-30 00:24

    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.

    0 讨论(0)
  • 2020-11-30 00:24

    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

    0 讨论(0)
提交回复
热议问题