Is there a definite source on variable capture in Javascript besides the standard (it's a pain to read the standard)?
In the following code i
is copied by value:
for (var i = 0; i < 10; i++) { (function (i) { process.nextTick(function () { console.log(i) }) }) (i) }
So it prints 1..10. process.nextTick
is an analog of setTimeout(f,0)
in node.
But in the next code i doesn't seem to be copied:
for (var i = 0; i < 10; i++) { var j = i process.nextTick(function () { console.log(j) }) }
It prints 9 10 times. Why? I'm more interested in a reference/general article than in explaining this concrete case of capture.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
What is Closure? A Closure is a function defined within another scope that has access to all the variables within the outer scope. A Closure allows us a free environment for the outer function to access the inner functions and inner variables without any scope restrictions.
Advantages of closures Variables in closures can help you maintain a state that you can use later. They provide data encapsulation. They help remove redundant code. They help maintain modular code.
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables — a scope chain. The closure has three scope chains: it has access to its own scope — variables defined between its curly brackets. it has access to the outer function's variables.
I don't have a handy reference. But the bottom line is: In the first, you're explicitly passing in i
to an anonymous function, which creates a new scope. You are not creating a new scope for either i
or j
in the second. Also, JavaScript always captures variables, not values. So you would be able to modify i too.
The JavaScript var
keyword has function scope, not block scope. So a for loop does not create a scope.
As a note, the non-standard let
keyword has local scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With