Sentence separated by comma in an IF Javascript would have what purpose? " if (1, 2) {}"

Asked

Viewed 334 times

4

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

I altered if (that.busy || that.completed) return; for if (that.busy, that.completed) return; unintentionally, and I noticed that it did not generate any syntax error.

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

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);
}

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

I wonder what that’s for.

2 answers

6


In this case your condition if assesses only the last case, as a normal operation with operator ,, namely a Sequence Expression.
There is 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 operator’s defection ,:

The comma 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 would be perhaps:

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

that never gets inside the if because the condition returns false. To be correct perhaps the ideal was double parentheses: if ((1, 2, false)) not to mix the syntax of if with the operator syntax ,, but it seems to work well this way "shortcut".

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

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

3

It was easier for me to understand like this:

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.

  • I think this last sentence needs to be better elaborated. I didn’t want to edit to be invasive.

  • @Wallacemaxters can edit my English not very good.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.