This is my first stackoverflow post! I am sorry if I botch the protocol on how to post. Let me know if I have :-)
I am working through this exercise in Head First Javascript and I don't know why an alternative won't work.
We iterate through passengers in order to find the type of ticket. Depending on the ticket we will provide a different alert: firstclass or else.
In this exercise, at function createDrinkOrders , we are calling a function (orderFunction) in order to provide alert.
Why does this not work if I DO NOT use the orderFunctions in createDrinkOrders?
I removed the orderFunctions in createDrinkOrders, but it alerts two or three times. If I include the orderFunctions in createDrinkOrders, it alerts 12 times. Why do we need the orderFunctions function here?
I imagine that after the iteration the alert, with or without the orderFunction, would produce the same result, but it doesn't why?
let passengers = [{
name: "Jane Doloop",
paid: true,
ticket: "coach"
},
{
name: "Dr. Evael",
paid: true,
ticket: "firstclass"
},
{
name: "Sue Propert",
paid: false,
ticket: "firstclass"
},
{
name: "John Funcall",
paid: true,
ticket: "coach"
}
];
function createDrinkOrders(passenger) {
let orderFunction;
if (passenger.ticket === "firstclass") {
orderFunction = function() {
alert("Would you like a cocktail or wine?")
}
} else {
orderFunction = function() {
alert("Your choice is cola or nothing!")
};
}
return orderFunction;
};
function serveCustomer(passenger) {
let getDrinkOrderFunction = createDrinkOrders(passenger);
getDrinkOrderfunction();
getDrinkOrderFunction();
getDrinkOrderFunction();
getDrinkOrderFunction();
};
function servePassengers(passengers) {
for (let i = 0; passengers.length; i++) {
serveCustomer(passengers[i]);
}
};
servePassengers(passengers);
Now the code without the orderFunction... See createDrinkOrders(passengers).
let passengers =[{name: "Jane Doloop", paid: true, ticket: "coach"},
{name: "Dr. Evael", paid: true, ticket: "firstclass"},
{name: "Sue Propert", paid: false, ticket: "firstclass"},
{name: "John Funcall", paid: true, ticket:"coach"}];
function createDrinkOrders(passenger){
if(passenger.ticket === "firstclass"){
alert("Would you like a cocktail or wine?")
}else{
alert("Your choice is cola or nothing!")
}
};
function serveCustomer (passenger){
getDrinkOrderfunction();
getDrinkOrderfunction();
getDrinkOrderfunction();
getDrinkOrderfunction();
};
function servePassengers (passengers){
for(let i = 0; passengers.length; i++){
serveCustomer(passengers[i]);
}
};
servePassengers(passengers);
getDrinkOrderfunctionisundefined.