Skip to content

Instantly share code, notes, and snippets.

@rewonc
Created December 9, 2014 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rewonc/fee5ebfb2f83e3ba8dac to your computer and use it in GitHub Desktop.
Save rewonc/fee5ebfb2f83e3ba8dac to your computer and use it in GitHub Desktop.
IIFE in loop vs pure functional version
// imperative version
var i,
callLater = {};
for (i = 0; i < 3; i++) {
(function (val) {
callLater[val] = function () {
return "hello " + val;
};
}(i));
}
console.log(callLater[0]()); // hello 0
console.log(callLater[2]()); // hello 2
// pure functional version
var sayHello = function (text) {
return ("hello " + text);
};
var cacheDefaultFor = function (func) {
return function (arg) {
return function () {
return func(arg);
};
};
};
var sayHelloWithValue = cacheDefaultFor(sayHello);
console.log(sayHelloWithValue(0)()); // hello 0
console.log(sayHelloWithValue(2)()); // hello 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment