Comma-separated sentence in an IF Javascript would have what purpose? "If (1, 2) {}"

4

By accident when I was changing a Javascript code I made, I put a comma instead of || in a if expression.

I changed if (that.busy || that.completed) return; to if (that.busy, that.completed) return; unintentionally, and noticed that it did not generate any syntax errors.

In addition, I did other tests that did not generate errors either:

var a = 1,   
    b = 2;

if (a, b) {
    console.log('a', 'b');
}

if (1, b) {
   console.log(1, 'b');
}


if (1, 2, 3) {
     console.log(1, 2, 3);
}

So, I did not understand why Javascript would accept this. But probably this should have the purpose.

I wonder what this is for.

    
asked by anonymous 02.12.2016 / 11:59

2 answers

6

In this case, your if condition evaluates only the last case, such as a normal operation with , operator, that is a Sequence Expression .
There's another question / answer that talks about it here .

What happens in the example

if (1, 2, 3) {
     console.log(1, 2, 3);
}

is:

if (3) console.log(1, 2, 3);

because it says the definition of the , operator:

  

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

     

The operator , evaluates the expressions of its operands, from left to right, and returns the value of the last operand.

A clearer example might be:

if (1, 2, false) {
     console.log(1, 2, 3);
}

that never goes inside if because the condition returns false . To be correct maybe the ideal would be double parenthesis: if ((1, 2, false)) not to mix the syntax of if with the syntax of the , operator, but it seems to work fine this way "shortcut."

There is an excellent tool for reading JavaScript AST. In this case you can read the following abstract syntax tree:

{
      "type": "IfStatement",
      "start": 4,
      "end": 55,
      "test": {
        "type": "SequenceExpression",
        "start": 8,
        "end": 15,
        "expressions": [ ... os operandos ...]
    
02.12.2016 / 12:16
3

It was easier for me to understand this way:

var test = 5;
if(test+=5,test-=6,test==10){
    console.log(test);
}else{
    console.log(test);
}

Anything before the last expression is executed, but the if only uses the last expression to decide whether the result is true or false.

    
02.12.2016 / 12:21