Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a closed-over variable mean? [duplicate]

Tags:

javascript

The example below was taken from a StackOverflow answer which helps to identify a closure.

for (var i = 0; i < 10; i++) {
    (function f() {
        var i2 = i;
        setTimeout(function g() {
            console.log(i2);
        }, 1000);
    })();
}

The following explanation was given:

For g:

List the variables: console is a free variable. i2 is a free variable. Find the parent scope to which each free variable is bound: console is bound to the global scope. i2 is bound to the scope of f. In which scope is the function referenced? The scope of setTimeout. Hence console is not closed over by g. Hence i2 is closed over by g.

However I am not able to understand the bolded part - could you explain it to me?

like image 635
user3601733 Avatar asked Feb 03 '26 05:02

user3601733


1 Answers

The term "closed-over" variable in that post means that the variable is not accessible by the caller of the function; it is neither seen nor modifiable from the context where the function is being called. Let's modify the code slightly:

var mySetTimeout = function (func, timeout) {
    console.log = function (arg) { alert(arg); };
    i = "foobar";
    i2 = "barfoo";
    setTimeout(func, timeout);
};

var i = "peekaboo";

(function f() {
    var i2 = i;
    mySetTimeout(function g() {
        console.log(i2);
    }, 1000);
})();

Instead of setTimeout, the function f calls mySetTimeout that tries to change both the value being logged after the timeout elapses, and the logging function.

After the function f has been called and it has returned, only the function g can see and modify the variable i2. However console is not closed over, because it is a value in the global scope; if you execute console.log = function (i) { alert(i); };, you will get alert box when the timeout fires. However, you cannot read or modify i2 in myTimeout - that function does not see the same variable at all.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!