Skip to content

Instantly share code, notes, and snippets.

@ddeveloperr
Created March 30, 2015 07:14
Show Gist options
  • Save ddeveloperr/210d996ae81f8e6933be to your computer and use it in GitHub Desktop.
Save ddeveloperr/210d996ae81f8e6933be to your computer and use it in GitHub Desktop.
Closure in JS examples
//
function wrapValue(n) {
var localVariable = n;
return function() { return localVariable; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
// Example 2
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
// More examples : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment