Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created June 13, 2013 19:16
Show Gist options
  • Save gavinblair/5776514 to your computer and use it in GitHub Desktop.
Save gavinblair/5776514 to your computer and use it in GitHub Desktop.
I have a bunch of loops, for different arrays. I just need some counters. When I do this, jshint says my variables k and l are already defined. Should I move on to other letters of the alphabet? Is there a better way?
for(var k in myarray){
for(var l in myarray[k]){
//do something with myarray[k][l]
}
}
for(var k in someotherarray){
for(var l in someotherarray[k]){
//do something with someotherarray[k][l]
}
}
@berdandy
Copy link

You can use function scoping. This gives an additional overhead of a closure, with attending allocations and deallocations, but it's quick and dirty, and a more universal solution that the resetting solution @SeanJA gives.

(function(){
for(var k in something) {
// ...
}
})();

(function(){
for(var k in somethingElse) {
// ...
}
})();

However, it's arguably better to just use variable names that have more meaning... somethingIdx, somethingElseIdx for instance. Or simply resetting. :)

@Cyborg572
Copy link

You're over-thinking it, you just can't declare the variable every time:

var k;
var l;

for(k in myarray){
    for(l in myarray[k]){
        //do something with myarray[k][l]
    }
}

for(k in someotherarray){
  for(l in someotherarray[k]){
        //do something with someotherarray[k][l]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment