Akki619
Akki619

Reputation: 2432

How does JavaScript evaluate operator precedence in this scenario?

I have below code and I just wanted to understand how the operator precedence working in this scenario. Just wanted to go back to old school and see how it works in JavaScript.

var num1 = 5,
    num2 = 10,
    result = (num1++)+num2;
    result1 = num1+++num2;
    result2 = (++num1)+num2;

console.log(result);
console.log(result1);
console.log(result2);

The above is printing as

15 
16
18

respectively.

  1. Shouldn't result1 be throwing a syntax error?
  2. I did not get how result2 is 18.

Upvotes: 0

Views: 56

Answers (1)

dave
dave

Reputation: 64657

result1 = num1+++num2;

is the same as

result1 = (num1++) + num2;

So essentially, what is happening is:

var num1 = 5,
    num2 = 10,
    result = (num1++) + num2; //5 + 10, then 5->6
    result1 = (num1++) + num2; //6 + 10, then 6->7
    result2 = (++num1) + num2; // 7->8, then 8 + 10

Upvotes: 4

Related Questions