Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Created February 23, 2017 13:05
Show Gist options
  • Save ivan-ha/7d2d1d771039ae00b340b5d56372c413 to your computer and use it in GitHub Desktop.
Save ivan-ha/7d2d1d771039ae00b340b5d56372c413 to your computer and use it in GitHub Desktop.
Function factory using closure in js
function makeGreeting(language) {
return function (name) {
if (language == 'en') {
console.log('Hello ' + name);
}
else if (language == 'es') {
console.log('Hola ' + name);
}
};
}
// each function call will create its closure with the language passed
// so the 'language' for greetEnglish and greetSpanish will be different
var greetEnglish = makeGreeting('en');
var greetSpanish = makeGreeting('es');
greetEnglish('foobar'); // Hello foobar
greetSpanish('foobar'); // Hola foobar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment