What is wrong with my javascript scope? [duplicate]

Javascript has function scope. This means that

for(...) {
    var j = i;
}

is equivalent to

var j;
for(...) {
    j = i;
}

In fact, this is how Javascript compilers will actually treat this code. And, of course, this causes your little “trick” to fail, because j will be incremented before the function in setTimeout gets called, i.e. j now doesn’t really do anything different than i, it’s just an alias with the same scope.

If Javascript were to have block scope, your trick would work, because j would be a new variable within every iteration.

What you need to do is create a new scope:

for(var i = ...) {
    (function (j) {
        // you can safely use j here now
        setTimeout(...);
    })(i);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)