Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't JavaScript support closures with local variables? [duplicate]

I am very puzzled about this code:

var closures = []; function create() {   for (var i = 0; i < 5; i++) {     closures[i] = function() {       alert("i = " + i);     };   } }  function run() {   for (var i = 0; i < 5; i++) {     closures[i]();   } }  create(); run(); 

From my understanding it should print 0,1,2,3,4 (isn't this the concept of closures?).

Instead it prints 5,5,5,5,5.

I tried Rhino and Firefox. Could someone explain this behavior to me?

like image 474
qollin Avatar asked Mar 13 '09 16:03

qollin


People also ask

Is closure unique to JavaScript?

Closures are a very powerful yet underused feature unique to of JavaScript (and other ECMAScript languages). They essentially provide your code with private variables that other scripts can't access.

How does closures work in JavaScript?

A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.

Which of the following are closures in JavaScript Mcq?

Explanation: In JavaScript, closures are created every time a function is created, at function creation time. Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them. 5. Which of the following uses a lot of CPU cycles?


1 Answers

Fixed Jon's answer by adding an additional anonymous function:

function create() {   for (var i = 0; i < 5; i++) {     closures[i] = (function(tmp) {         return function() {           alert("i = " + tmp);         };     })(i);   } } 

The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.

After the loop terminates, the function-level variable i has the value 5, and that's what the inner function 'sees'.


As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer.

like image 60
Christoph Avatar answered Oct 07 '22 22:10

Christoph