Bader Iddeen Idrees
Bader Iddeen Idrees

Reputation: 13

Does unary set the variable to its initial value

After calculating the result of this code, I wonder if the unary sets my vars as "uno" here to its original state, and if it does, how about negative unaries

let uno = 10, dos = "20", tres = 80;
console.log(++uno + +dos++ + +tres++ - +uno++);

my conclusion was the equation of 103, as 11 + 21 + 81 - 10, but it's appearing not to be true!

Upvotes: 0

Views: 56

Answers (1)

Barmar
Barmar

Reputation: 780852

The unary operator has lower precedence than the increment operators. So +dos++ is treated as +(dos++). In this case, the unary operator is redundant, because the increment operator converts the value to a number first (it makes little sense to increment a string).

Since you're using the post-increment operator on dos and tres, the values of those subexpressions are the original numeric values; see javascript i++ vs ++i. So you're adding 20 and 30, not 21 and 31.

When you subtract uno++ at the end, this happens after the increment from ++uno. So the value being subtracted is 11, not 10.

The entire thing is effectively equivalent to:

let uno = 10, dos = "20", tres = 80;
let uno1 = ++uno; // uno1 = 11, uno = 11
let dos1 = dos++; // dos1 = 20, dos = 21
let tres1 = tres++; // tres1 = 80, tres = 81
let uno2 = uno++; // uno2 = 11, uno = 12
console.log(uno1 + dos1 + tres1 - uno2); // 11 + 20 + 80 - 11 = 100

Upvotes: 3

Related Questions