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);

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);


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.:


then you can omit the name, thus avoiding the creation of an unnecessary variable.


Leave a comment

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