-6

var x = 5;
x *= 2;
console.log(++x);

How is the answer 11? I'm confused

tonitone120
  • 1,920
  • 3
  • 8
  • 25

3 Answers3

1
var x = 5; // x = 5
x *= 2; // multiply x with 2 (x = 10)
console.log(++x); // console.log x plus 1 (11)

A more common way of using this syntax is with plus or minus:

x += 1;
// is a shorthand for
x = x + 1;

x *= 2;
// is a shorthand for
x = x * 2;

// etc.
Dom
  • 734
  • 3
  • 8
0

++x increments FIRST, and THEN is used, vs:
x++ which is used FIRST, THEN is incremented.

if x is 10,
console.log(++x) will result in "11", vs:
console.log(x++) will result in "10".

In both cases, after code line, x will be 11.

iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

var x = 5;
x *= 2;
console.log(x);
console.log(++x);

x *= 2; says: x will be reinitialised (reassigned) to what it was before (5) multiplied by 2 (which gives us 10). (Useful link - look at chapter Modify-in-place)

++x says: x will be reinitialised (reassigned) to what it was before (10) plus 1. Also, return xs new value (11). (In same link, look at the below chapter Increment/Decrement)

If, instead, we had x++ it'll say: 'add 1 to x but don't return this new value - return the value before we made this addition (10):

var x = 5;
x *= 2;
console.log(x++);
tonitone120
  • 1,920
  • 3
  • 8
  • 25