I know that JavaScript vars point to a value:
var foo = true;
//... later
foo = false;
So in that example I’ve changed foo pointing to true -> foo pointing to false, but if I do:
for (var i=0; i<100; i++){
var someVar = i;
}
Am I creating a new var for each iteration?
Is there any difference in the following two ways of doing the same?
var myvar;
for (var i=0; i<100; i++){
myvar = i;
}
and
for (var i=0; i<100; i++){
var myvar = i;
}
If so, why?
There is no block scope in Javascript ES5 and earlier, only function scope. Furthermore, the declarations of all javascript variables declared within a function scope are automatically “hoisted” to the top of the function.
So, declaring a variable within a loop isn’t doing anything different than declaring it at the top of the function and then referencing it within the loop.
See these two references for some useful explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting and http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/.
Note: the assignment to a variable is not hoisted, just the declaration of the variable. So, if you do this:
It works like this:
If you wanted to create a new scope inside your
forloop, you could use an IIFE (immediately invoked function expression) like this:Update in 2015. ES6 (or sometimes called ES2015) offers the
letdeclaration which does offer block scope. In that case aletvariable declaration is hoisted only to the top of the current block scope. As of mid 2015, this is not yet widely implemented in browsers, but is coming soon and it is available in server-side environments like node.js or via transpilers.So, in ES6 if you did this:
Both
iandsomeVarwould be local to the loop only.