According to jsLint it is recommended to declare for loop in the following way:
for(var i = 0, length = data.length; i < length; i+=1){...}
What is the difference between i++
and i+=1
in this context?
Any help will be appreciated!
There is no functional difference in this context. However ++
and --
can be a source of bugs by complicating code and causing off-by-one errors (preincrement and postincrement confusion). Hence JSLint recommends against using this construct.
JSLint isn't telling you your code is functionally wrong, it's pointing out that there is another way to write it that avoids common pitfalls.
In fact, the latest version of JSLint will recommend against using for
at all, because array instance methods such as forEach
and map
should be preferred (obviously there is a flag to turn this off when necessary).
This and other recommendations are explained in the JSLint instructions.
There is absolutely no difference. But if you use i++
you'll save a byte. And if you skip declaring length
you'll save even more.
So.. I don't see why you'd use it that way. Here's how I always do it:
for (var i = 0; i < arr.length; i++) {
...
}
On the topic of saving bytes here, if your loop looks like this:
for (var i = 0; i < arr.length; i++) {
var e = arr[i];
}
You could also do this:
for (var i = 0; i < arr.length;) {
var e = arr[i++];
}
You could also do this:
arr.forEach(function(e) {
// ...
});
This assumes you don't need to use the index of e
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With