I remember variables are function scoped in Javascript. But, how is the behavior if I redefine the local variable in a loop. One common use case is nested loops. In the bel
There's no block level scope in JS.
But if it's utmost necessary to have/re-declare the same variable name in your code, you can do:
function loopIt(arr, fn, scope) {
for (var i = 0, len = arr.length; i < len; i++) {
fn.call(scope || this, arr[i], i, arr);
}
}
And use it like:
var firstArr = ["a", "b"];
var secondArr = ["c", "d"];
loopIt(firstArr, function(item, i) {
var msg = "Hey it's '" + item + "'";
console.log(msg);
// if you want access to the parent scope's var
var scopedItem = item;
loopIt(secondArr, function(item, i) {
var msg = "Hello it's '" + item + "' in '" scopedItem + "'";
console.log(msg);
});
});
That will give us results of:
Hey it's 'a'
Hello it's 'c' in 'a'
Hello it's 'd' in 'a'
Hey it's 'b'
Hello it's 'c' in 'b'
Hello it's 'd' in 'b'