Function Expressions
Function declarations
function catSays(max) {
//function contents
}
catSays();
Function expressions
var catSays = function(max) {
//function contents
};
catSays();
Once you know how to declare a function, a whole new set of possibilities will open up to you.
For instance, remember how you can store anything you want in a variable? Well, in JavaScript, you can also store functions in variables. When a function is stored_inside_a variable it's called afunction expression.
var catSays = function(max) {
var catMessage = "";
for (var i = 0; i < max; i++) {
catMessage += "meow ";
}
return catMessage;
};
Notice how thefunction
keyword no longer has a name.
var catSays = function(max) {
// code here
};
It's ananonymous function, a function with no name, and you've stored it in a variable calledcatSays
.
And, if you try accessing the value of the variablecatSays
, you'll even see the function returned back to you.
catSays;
Returns:
function(max) { var catMessage = "" for (var i = 0; i < max; i++) { catMessage += "meow "; } return catMessage; }
Function expressions and hoisting
Deciding when to use a function expression and when to use a function declaration can depend on a few things, and you will see some ways to use them in the next section. But, one thing you'll want to be careful of, is hoisting.
Allfunction declarations are hoisted_and loaded before the script is actually run._Function expressions are not hoisted, since they involve variable assignment, and only variable declarations are hoisted. The function expression will not be loaded until the interpreter reaches it in the script.