Returning functions from functions in JavaScript

Maria Blair

I'm learning how to return functions from other functions in JavaScript. Here is my code that works:

var passengers = [
    { name: "Jane", ticket: "coach" },
    { name: "Evel", ticket: "firstclass" },
    { name: "John", ticket: "coach" },
    { name: "Bob", ticket: "premium"}
];

function createDrinkOrder(passenger) {
    var orderFunction;
    if (passenger.ticket === 'firstclass') {
        orderFunction = function() {
            console.log(passenger.name + ', would you like wine or cocktail?');
        };
    } else if (passenger.ticket === 'premium') {
        orderFunction = function() {
            console.log(passenger.name + ', would you like some wine?');
        };
    } else {
        orderFunction = function() {
            console.log(passenger.name + ', soda or water?');
        };
    }
    return orderFunction;
}

function serveOnePassenger(passenger) {
    var getDrinkOrderFunction = createDrinkOrder(passenger);
    getDrinkOrderFunction();
    // createDrinkOrder(passenger);
}

// General function to serve passengers:
function servePassengers(passengers) {
    for (var i = 0; i < passengers.length; i++) {
        serveOnePassenger(passengers[i]);
    }
}

servePassengers(passengers);  

My question is about 'serverOnePassenger' function: when I comment out the first 2 lines in this function and uncomment the 3rd line instead, nothing happens in the console anymore. Why do I have to declare a variable and then assign a function to it, and only then call this var in order for this code to work? Thanks!

Pointy

Your own question title is basically the answer: you've written the createDrinkOrder() function as something that returns another function. If you make a function but never call it, the function won't do anything.

You don't need a variable involved as in your serveOnePassenger() function. You could create the function and call it with one statement:

  createDrinkOrder(passenger)();

That calls createDrinkOrder() and then immediately uses the returned value as a function.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related