how How do JavaScript variables work?

 

Questions


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?

 

 

————————————————-

Answer

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:

function a() {
    for (var i=0; i<100; i++){
        var myvar = i;
    }
}

It works like this:

function a() {
    var myvar;
    for (var i=0; i<100; i++){
        myvar = i;
    }
}

If you wanted to create a new scope inside your for loop, you could use an IIFE (immediately invoked function expression) like this:

function a() {
    for (var i=0; i<100; i++){
        (function() {
            var myvar = i;
            // myvar is now a separate variable for each time through the for loop
        })();
    }
}

Update in 2015. ES6 (or sometimes called ES2015) offers the let declaration which does offer block scope. In that case a let variable 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:

for (let i=0; i<100; i++){
    let someVar = i;
}

Both i and someVar would be local to the loop only.

javascript,scope,var,variables

Facebook Comments

Post a comment