0

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?

Community
  • 1
  • 1
Jason Ruby
  • 33
  • 1
  • 6
  • Possible duplicate of [How to increment number by 0.01 in javascript using a loop?](http://stackoverflow.com/questions/19290628/how-to-increment-number-by-0-01-in-javascript-using-a-loop) – Mahi Nov 23 '16 at 19:47

2 Answers2

1

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++.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • Thank you Timo! As soon as I saw the addition assignment operator `+=`I knew what you were talking about. That makes a lot more sense seeing what wrote versus what I wrote. Also, thank you for the explanation of when it would increment, e.g. `++i` versus `i++`. I am still not used to assignment operators. I understand them, however I forget about them and when I see one I have to pause and remember how they operate. – Jason Ruby Nov 23 '16 at 20:00
0

To add to Timo's answer, I wouldn't recommend using fractional increments in a loop, because it can lead to rounding errors:

for (var i = 0; i <= 1; i += 0.1) {
    console.log(i);
}

// 0
// 0.1
// 0.2
// 0.30000000000000004
// 0.4
// 0.5
// 0.6
// 0.7
// 0.7999999999999999
// 0.8999999999999999
// 0.9999999999999999

Instead you can use integer increments, and then scale the value to the desired range:

for (var i = 0; i <= 10; i++) {
    console.log(i / 10);
}

// 0
// 0.1
// 0.2
// 0.3
// 0.4
// 0.5
// 0.6
// 0.7
// 0.8
// 0.9
// 1
Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47