Reputation: 33
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:
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?
Upvotes: 0
Views: 299
Reputation: 12197
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
Upvotes: 0
Reputation: 42460
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++
.
Upvotes: 1