Reputation: 1435
What exactly goes into an if statement's parens?
If I have:
if(setX(), x === 5)
Does that get interpreted as:
if((setX(), x) === 5) // which is the same as:
setX(); if(x === 5)
Or does it get interpreted as:
if((setX()), (x === 5))
(which is ultimately the same thing, but I'm still curious about the syntax.)
Upvotes: 0
Views: 105
Reputation: 27833
There are 3 things happening inside those parenthesis, in this order:
Code taken step by step:
// setup
function setX(){
return 3;
}
x = 4;
// steps
if (setX(),x === 5)
// evaluate function call
if (3,4 === 5)
// evaluate equality comparison
if (3,false)
// evaluate comma operator
if (false)
// jump to the appropriate code branch
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Upvotes: 1
Reputation: 5041
The comma operator evaluates its two operands and returns the value of the right operand. Therefore your if statement will be the result of the x === 5 test performed after the setX() function.
Whether this is good programming style is however open to debate .... :-)
Upvotes: 1
Reputation: 272236
Comma has the least priority, so:
setX()
will be evaluated firstx === 5
will be evaluated secondif
statement checks for x === 5
Upvotes: 1