Why should I return a function as a value from another function?


#1

For example, I’m building a queue application in ember that’s based off of the queue in the Javascript Road Trip course from Code School if anyone is familiar.

Here’s an example function I’m using:

function buildTicket(allRides, passRides, pick) {
  if (passRides[0] == pick) {
    var pass = fastAvail.shift();
    return function( ) { alert("Quck! You've got a pass to " + pass + "!");
              }
}

My question is, why should I return an anonymous function expression over simply returning an alert() ?

 function buildTicket(allRides, passRides, pick) {
  if (passRides[0] == pick) {
    var pass = fastAvail.shift();
    return alert("Quck! You've got a pass to " + pass + "!");
}

What is the benefit of returning a function?


#2

Well.

var a = function() { alert(“run”) }; a(); a();

You can keep reusing the function by returning a anonymous call. If you choose to return alert(‘a’) you will get undefined.

var a = alert('a) console.log(a); //undefined

That’s what I can think of.