user2958725
user2958725

Reputation: 1435

Syntax of if statement and operator precedence

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

Answers (3)

Tibos
Tibos

Reputation: 27833

There are 3 things happening inside those parenthesis, in this order:

  1. function call
  2. equality comparison
  3. comma operator

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

vogomatix
vogomatix

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

Salman Arshad
Salman Arshad

Reputation: 272236

Comma has the least priority, so:

  • setX() will be evaluated first
  • x === 5 will be evaluated second
  • the if statement checks for x === 5

Upvotes: 1

Related Questions