I am a beginning JS programmer working through codeschool's 3rd JS course. One of their modules introduces the concept of passing function expression variables as parameters for other functions. However, I need some help understanding why this method is better in some cases than in others. For example, the following code is for a conditional alert that is supposed to recognize whether the user is a new user and throw a customized greeting when the user logs out of the system.
This is what codeschool advocates:
var greeting;
var newCustomer;
//Some code sets the variable newCustomer to true or false
if( newCustomer ){
greeting = function () {
alert("Thanks for visiting the Badlands!\n" +
"We hope your stay is...better than most.");
};
} else {
greeting = function () {
alert("Welcome back to the Badlands!\n" +
"Guess they aren't so bad huh?");
};
}
closeTerminal( greeting );
function closeTerminal( message ){ message();}
But why is that better than the following?
var greeting;
var newCustomer;
//Some code sets the variable newCustomer to true or false
closeTerminal();
function closeTerminal(){
if( newCustomer ) {
alert("Thanks for visiting the Badlands!\n" +
"We hope your stay is...better than most.");
} else {
alert("Welcome back to the Badlands!\n" +
"Guess they aren't so bad huh?");
}
}
Which of these code blocks (or any other code) would a good developer use to achieve the desired result? Is there an advantage to storing an entire function in a variable over just using a single if . . . else
statement to evaluate newCustomer and return the desired greeting?