Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding variable capture by closures in Javascript/Node

Tags:

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.

like image 759
nponeccop Avatar asked Apr 10 '12 19:04

nponeccop


People also ask

How will you explain closures in JavaScript?

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 function in node JS?

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.

What is the advantage of using closures in JavaScript?

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.

What kind of access closure variable have?

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.


1 Answers

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.

like image 178
Matthew Flaschen Avatar answered Dec 21 '22 10:12

Matthew Flaschen