Immediately Executing an Anonymous Function in JavaScript

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:

an alert dialog on a web page with the words Eat apples

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.

So why use an Anonymous 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.

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.