Blue Paw Blue Paw - 14 days ago 4
Javascript Question

JavaScript: Dividing Pre- and Postfix Increment/Decrement

This may be a strange question as I don't have a specific example in mind. I am in the process of trying to learn JavaScript and while reviewing some material I began wondering if it is possible to increment/decrement by less than one (1).
In other words if there were a situation where you needed to increment a variable by something other that "1". E.g. incrementing the variable i by 0.5 as opposed to 1,

for (var i = 0, i < 10.5, i++/2) {...

As I said, I don't have a specific example or reason for needing to do this. I am just curious if:


  1. It is legal within JavaScript?

  2. Is this something that would possibly come up in a real scenario?

  3. If so, is this the correct way of doing it, or is there a
    different/better way to increment/decrement by a fractional number?



Thank you in advance for any response!

Not the same question as the issue experienced in How to increment number by 0.01 in javascript using a loop?

Answer

i++/2 is valid syntax, however it won't do what you expect.

Instead, the expression i += 0.5 will increment i by 0.5 and return the new value:

var i = 1
var x = (i += 0.5)

console.log(i) // 1.5
console.log(x) // 1.5

+= is called the addition assignment operator. Note that the expression will return the incremented value, not the value of i before the change. In other words, it behaves similar to ++i, not to i++.