user2998413
user2998413

Reputation: 73

why function expression has been used when we could've used simple return statement

While I learn javascript, I;m very confused about using function expression. I understand the grammar syntax of it but just not sure the purpose of this. For example here

return function(){ alert("Quick! You've got a Fast Pass to " + pass + "!");};

can't we just use return and then the statement. I'll post where this code is from

var parkRides = [["Birch Bumpers", 40], ["Pines Plunge", 55],
                ["Cedar Coaster", 20], ["Ferris Wheel of Firs", 90]];

var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];
var wantsRide = "British Bumpers";
function buildTickets(allRides, passRides, pick) {
  if(passRides[0] == pick) {
    var pass = passRides.shift();
    return function(){ alert("Quick! You've got a Fast Pass to " + pass + "!");};
  } else {
    for(var i = 0; i < allRides.length; i++){
      if(allRides[i][0] == pick){
        return function() { alert("A ticket is printing for " + pick + "!\n" + "Your wait time is about " + allRides[i][1] + "minutes. ");};
      }
    }
  }
}
var ticket = buildTickets(parkRides,fastPassQueue, wantsRide)();
tickets();

I mean we can still use the variable pass since it's in the same function even without new function(). why do we need to use closure as well here?

Upvotes: 0

Views: 37

Answers (1)

Varinder
Varinder

Reputation: 2664

Sometimes you want control exactly when to run certain logic (in above case alert) by returning a function you can then control when you can alert by calling tickets

Imagine if user has set a preference to not see alert messages, the logic would be as simple as: isAlertAllowed ? tickets() : null

Upvotes: 1

Related Questions