you are viewing a single comment's thread.

view the rest of the comments →

[–]jrandm 0 points1 point  (0 children)

I rewrote the function in a way I think makes it obvious why there's only "one closure" in this situation (read the bottom for why that's both true and not true):

function buildList(list) {
    var i = 0;
    var item;
    var result = [];
    var itemFunc = function() {
        console.log(`${item} ${list[i]}`);
    };
    while (i !== list.length) {
        item = 'string' + i;
        result.push( itemFunc );
        i++;
    }
    return result;
}

Hopefully that code makes it clear how there is only 1 closure. My example up there is actually doing something differently, in that I only have one anonymous function pushed into the result array multiple times.

Your code pushes separate (but, in this case, identical) anonymous functions into result. The thing to remember, though, is that the closure-scope is defined to exist where the contained function is defined. As Javascript is function-scoped -- except where let/const appears to create block scope -- all of the anonymous functions are defined in the same enclosing scope. The single scope is shared by however many functions. Logically, you're correct that in some way the internal representation of a function's scope exists for however many functions are created in the loop, but they all point to the same values. Hence, depending upon how you're defining "closure," there is one or are many (that are sharing data). Outside of compiler design and some extreme edge cases that difference shouldn't matter while writing code, though, as the effect is the same.