Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Great question! Every time you call foo, a new scope containing x is created. That scope "travels" with bar, and is evaluated (dereferenced might be a better word) just as any other variable inside bar would be - during the execution of bar. A global variable is just a variable in the topmost ("global") scope.

But my example doesn't make the distinction to clarify that at all. Here's a better one:

    function colors() {
        var cs = ['red', 'green', 'blue'],
            i = 0;

        function nextcolor() {
            i = (i+1) % cs.length;
            return cs[i];
        }

        return nextcolor;
    }
Every time you call colors, a new local scope is created. Easiest way to think of scopes is as maps from strings to values. In this case, a new scope { cs: ['red', 'green', 'blue'], i: 0 } is created every time you calls colors. If the language didn't support closures, that scope would be destroyed when colors finishes execution, but in JS, that scope is bound to nextcolor and returned along with nextcolor in a closure. Now, every time you call a particular nextcolor returned by a call to colors, the cs and i variables will reference those same values. Example using firebug:

    >>> A = colors()
    >>> B = colors()
    >>> A() => "green"
    >>> A() => "blue"
    >>> B() => "green"
    >>> B() => "blue"
    >>> A() => "red"
    >>> A() => "green"
    ...
Keep asking if anything is unclear. I was wrong about this taking 1 minute, I suppose... :)


For the record: on second reading, I should have said "that scope is bundled with nextcolor and returned as a closure", not "bound to nextcolor", since the word "bound" is usually used to talk about variable names ("identifiers") and their values.

Similarly, in the next sentence, I should have pointed out that when you call the returned value, you're not just calling nextcolor but the closure over nextcolor, which includes the bindings for cs and i.


Your two javascript examples are fantastic. Thank you for explaining this in a very clear way.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: