If you come from a language that does not support first class functions, then it can be confusing when you encounter one that does. A first class function is one that can be passed to a function or returned from a function just as if it were ordinary data like a string or a number. The following code should shed some light:
var pet = function(name) { // assign anonymous func to pet
var getName = function() { // assign nested anonymous func to getName
console.log(name); // prints to console; no return value
};
return getName; // return getName value: func definition
};
myPet = pet("Vivie"); // assign getName value to myPet
myPet(); // appending () invokes defined func
"Vivie" gets passed to the function that pet holds, yet console.log()
prints it! This is accomplished by a feature known as a closure. Since name
exists in the nested function's immediate external environment, the variable binds to it and continues to exist even after the outer function (contained in pet) executes.
Aboutconsole.log()
, note it is incorrect to write it as part of a return statement because the logging method never returns a value; it just prints to the console. So with the following code:
var pet = function(name) {
var getName = function() {
return console.log(name);
}
return getName;
},
myPet = pet("Vivie");
console.log(typeof myPet());
in the last statement, myPet() executes causing "Vivie" to be printed to the console but it returns nothing. So, typeof returns "undefined" and that result, too, gets printed to the console. See http://jsfiddle.net/yu75k5tz/.
Returning to the main topic of passing a function, consider the previous snippet again. There is an alternate and more economical way to achieve the same result by using function call chaining, as follows:
pet("Vivie")();
The first set of parentheses invokes pet which returns a function, albeit anonymous. The second pair of parentheses cause the returned function to execute. This code eliminates having to assign getName to a variable, which in turn reduces two statements to this one-liner.
Finally, the trailing semi-colons of the function definitions may appear odd but they are syntactically correct. Each anonymous function is being assigned to a variable, so each of these semi-colons actually terminates an assignment statement.
Live demo here: http://jsfiddle.net/kLghedp3/8/