0

let x = 7; x++; x - 2; x *= 3; console.log(x);

I am currently trying to figure this code, but I am still struggling on how to solve it. Since X turns into 1 so would add 1 to all the X's? for example 1 - 2 is 1 and then 1 x 3 is 3? but how does it equal 24?

12th Mar 2023, 6:29 PM
Eren
3 Answers
+ 5
let x = 7; x++; // <x> is now 8 x - 2; // this expression has no effect, // and it doesn't modify <x>; // the expression is evaluated // but the evaluation result // isn't getting re-assigned to <x>. // things will be different had it // been x -= 2 because // -= operator subtracts LHS by RHS // and assign the result back to LHS x *= 3; // that's 8 * 3
12th Mar 2023, 6:51 PM
Ipang
+ 3
x - 2 is evaluated normally, but it has no effect on <x>, because the evaluation result isn't getting assigned back to <x>, Had we used x -= 2 instead, things will be different. Because x -= 2 acts like x = x - 2. The result from evaluation of `x - 2` is assigned back to <x>, after the subtraction. Effectively modifying <x> value. I'm not sure how JS handles expression parts once an evaluation is completed. But I'm guessing there would be some cleaning up being done behind the screen after the evaluation, automatically by garbage collector presumably.
12th Mar 2023, 7:36 PM
Ipang
+ 1
thank you so much! I really appreciate the explanation for this. since x - 2; did not re-assign to x, what happens to the 2? does 2 cancel out or does nothing?
12th Mar 2023, 7:05 PM
Eren