Asqan Asqan - 2 months ago 11
Javascript Question

Already defined error for functions with multiple for loops

I have following function:

self.aFunction = function(otherAll, all){
for(var i = 0; i < all.length; i++){
...
}
for(var i = 0; i < otherAll.length; i++){
...
}
return someResult;
};


I have two for loops and they both use the variable "i". They have nothing common and used for each loops separately.

However, i take the following error from jshint:

'i' is already defined.


What is wrong with this? Why is that important to use other variables for each loops in the same function? Is it an issue i should care about in this case?

Answer

In pragmatic terms, it's fine to reuse the same variable in your example, but by declaring it twice, you're giving the impression you think it's scoped to the for loop. It isn't, which is why JSHint is giving you that notice: To make sure that it's not actually a bug in the code.

If you want to reuse i, just declare it once:

self.aFunction = function(otherAll, all){
    var i;
    for(i = 0; i < all.length; i++){
        ...
    }
    for(i = 0; i < otherAll.length; i++){
        ...
    }
    return someResult;
};

Alternately, if all and otherAll are arrays, look at forEach or the many other options in my other answer here.


IF you're able to use ES2015 features (e.g., you know all your target environments support them, or you're transpiling), then:

You can use let:

self.aFunction = function(otherAll, all){
    for(let i = 0; i < all.length; i++){
        ...
    }
    for(let i = 0; i < otherAll.length; i++){
        ...
    }
    return someResult;
};

The i declared with let will be scoped to the for loop (in a very interesting way, no less).

Or if you don't need the index and just want the values in the loop, and all and otherAll are iterables (arrays are iterable), use let with the new for-of:

self.aFunction = function(otherAll, all){
    for(let value of all){
        ...
    }
    for(let value of otherAll){
        ...
    }
    return someResult;
};