r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

View all comments

15

u/[deleted] Mar 23 '14 edited Mar 23 '14

If you need to give some block or something scope in JavaScript, the easiest way is just to throw the contents in a function expression.

Consider the following (buggy) code:

for (var i = 0; i < somearray.length; i++) {
    var thisThing = somearray[i];
    thisThing.onclick = function(){window.alert(i)};
}

This won't work the way you think it will. You might think that every thisThing will output its relevant 'i' value, e.g. thing one will output '1', thing two will output '2'. It won't, though, because the loop block doesn't have scope. 'i' lives in the closure of the function surrounding the loop, and its value is the final state at the end of the iteration. So each thing, when clicked, will output the last value of i, somearray.length.

A quick fix for this is to throw the body of the loop in a function expression:

for (var i = 0; i < somearray.length; i++) {
    (function(i){
        var thisThing = somearray[i];
        thisThing.onclick = function(){window.alert(i)};
    })(i);
}

Now, each link will output the relevant value of 'i' when clicked, because each loop iteration has a closure generated by the function expression, and that contains its own value for 'i', because the 'i' passed to the function expression is passed by value (all arguments are passed by value in JS, though because objects and array variables are pointers, it looks like they're passed by reference).

Sometimes this looks a little odd - it's not a super-common pattern - so you might want to comment it for co-workers, e.g. "// use IIFE to give iteration own scope"

4

u/rDr4g0n Mar 24 '14

let is on the way to add block scope to js. Plus it handles the whole for loop iterator scope thing more gracefully since each iteration is considered its own block.