Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsLint for loop declaration

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!

like image 201
andrey Avatar asked Aug 02 '15 11:08

andrey


2 Answers

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.

like image 69
1983 Avatar answered Sep 29 '22 13:09

1983


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.

like image 35
Florrie Avatar answered Sep 29 '22 14:09

Florrie