Increments confusion

help, please

kindly explain this concept in full

Increments

If you only want to increment a value by 1, you can use the increment operator, ++. This goes either directly before the variable (prefix operator) or after it (postfix operator). Try entering the following code into the console to see how these work:

Copy

let points = 5;  points++;<< 5
++points;<< 7

So what’s going on here? Both operators increase the value of points by 1, even though it doesn’t immediately look like the first one has changed anything. The difference is when the increment takes place in relation to the value that’s returned.

In the first operation, points++ returns the original value of score, 5, then increases it to 6, whereas ++points increases the value by 1, then returns the new value of 7.

The difference is when the increment takes place in relation to the value that’s returned.

also, what does The difference is when the increment takes place in relation to the value that’s returned. mean?

++ will add 1 to a numerical variable.

where you put the ++ determines the value returned by the operation at the time.

You can either put the ++ after the variable, in which case the value returned is the value before addition:

let points = 5; //points is now 5.
console.log(points++); //This will output 5, but then set the value of points to 6.
console.log(points); //Outputs 6.

or you put it before the variable, which does the addition first, and then returns the value:

let points = 5; //points is now 5.
console.log(++points); //This will output 6 because it did the addition first.
console.log(points); //Outputs 6 still.
1 Like