In JavaScript, you can create and use functions without giving them a name:
(function(fruit) {
alert('Eat ' + fruit);
})('apples');
Above, we are creating and calling an anonymous function (one without a name) to alert the user to Eat apples.
Running this in Firefox, we see:
The following code:
function EatFruit(fruit) {
alert('Eat ' + fruit);
}
EatFruit('apples');
behaves the same way, but creates a global variable named EatFruit to store the function.
If you don't need to refer to the function multiple times, e.g.:
EatFruit('apples');
EatFruit('peaches');
EatFruit('mangos');
then you can omit the name, thus avoiding the creation of an unnecessary variable.
Leave a comment