Function Factories

// Copy and paste this post into your editor between the script using or console within the browser to follow the results. This is about how to create a Function Factory. This is nice. I can create a function called makeGreeting and it will call one of two functions, one in English and one in Spanish depending on the language parameter for makeGreeting.

function makeGreeting(language){
return function(firstname, lastname){
if (language ===‘en’){
console.log(‘Hello’ + firstname + ’ ’ + lastname);
if (language === ‘es’){
console.log(‘Hola’ + firstname + ’ ’ + lastname);



//Now I can create two variables one to greetEnglish and one to greetSpanish and then I can call either one depending if I want to greet in English or greet in Spanish. I can then call the vaiable which will call the makeGreeting function and sit there and wait for me to call the anynomous function by putting the first and lastname in parenthesis. This is using the concept of closures to create a function factory.

var greetEnglish = makeGreeting(‘en’);
var greetSpanish = makeGreeting(‘es’);

greetEnglish(" Imhotep ",“Amen Ra El”);

greetSpanish(" Imhotep ", "Amen Ra El ");

//Closuer and function expression example

function sayHiLater(){
var greeting = ‘Hi !’;


//Use JQuery using function expression and first -class functions but I dont have JQuery runnning so will make it a statement
// $(“button”).click(function(){
// });

function tellMeWhenDone(callback){

var a = 1000; //some work
var b = 2000; //some work

callback(); //the "callback", runs the function I give it


console.log(‘I am done!’);

alert(‘I am done!’);