Search code examples
javascriptloopsglobal-variablesonload

Variable, defined insde for loop of window.onload function, gets global scope at window level


I have a function set to window.onload event. Inside that function I have a for loop, that defines variable unit on every iteration as a new object of type GAME.Unit. As a result of this, I have a variable unit in window scope, holding last created object! I always thought, variables inside loop are loop-oriented. I double-checked and there are no other declarations on unit variable anywhere in my code. What am I doing wrong?

enter image description here


Solution

  • Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

    MDN.

    var scopes a variable to the function, not the loop.

    To scope a variable to a block, use let.