JSFiddle - React, Tailwind, and code Playground
by KelseyW
HTML
<div id="results"></div>
JavaScript
var $results = $('#results');
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// GOOD
$results.append('CLOSURES DONE RIGHT<br />');
var arr = [];
function createClosure(n) {
return function () {
return 'n = ' + n;
}
}
for (var index = 0; index < 10; index++) {
arr[index] = createClosure(index);
}
for (var index in arr) {
$results.append(arr[index]() + '<br />');
}
/*
- In the above code createClosure(n) is invoked in every iteration of the loop.
- This creates a new scope and n is bound to that scope; this means we have 10 separate scopes, one for each iteration.
- createClosure(n) returns a function that returns the n within that scope.
- Within each scope n is bound to whatever value it had when createClosure(n) was invoked so the nested function that gets returned will always return the value of n that it had when createClosure(n) was invoked.
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$results.append('<hr />');
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// BAD
$results.append('CLOSURES DONE WRONG<br />');
function createClosureArray() {
var badArr = [];
for (var index = 0; index < 10; index++) {
badArr[index] = function () {
return 'n = ' + index;
};
}
return badArr;
}
var badArr = createClosureArray();
for (var index in badArr) {
$results.append(badArr[index]() + '<br />');
}
/*
- In the above code the loop was moved within the createClosureArray() function and the function now just returns the completed array, which at first glance seems more intuitive.
- What might not be obvious is that since createClosureArray() is only invoked once only one scope is created for this function instead of one for every iteration of the loop.
- Within this function a variable named index is defined. The loop runs and adds...