Search code examples
javascriptfunctionvariablesfirst-class-functions

What are the differences between these two functions one uses first class? (javascript)


There are two functions one uses first class and assigning a function to a variable then returns the variable and the other one is just a regular simple function. In there, I don't get why is one better than the other one because they both looks and does the exact same thing to me. Can someone please give me a hand giving me an easier understanding the difference?

first class

function createDrinkOrder1(passenger) {
    var orderFunction;
    if (passenger.ticket === "firstclass") {
        orderFunction = function() {
            console.log("Would you like a cocktail or wine?");
        };
    } else {
        orderFunction = function() {
            console.log("Your choice is cola or water.");
        };
    }
    return orderFunction;
}

simple function

function createDrinkOrder2(passenger){
    if(passenger.ticket === "firstclass"){
        console.log("Would you like a cocktail or wine?");
    }else{
        console.log("Your choice is cola or water.");
    }   
}

Solution

  • createDrinkOrder1 returns a function that you can LATER call:

    var orderFunction = createDrinkOrder1(passenger);
    // nothing printed to console yet
    
    // later:
    orderFunction();
    // now printed to console
    

    createDrinkOrder2 immediatelly prints the results:

    createDrinkOrder1(passenger);
    // printed to console
    

    You sometimes return a function not only to be able to call it later, but also to create a closure, that might be an interesting topic to read about.