Your browser does not support JavaScript!
Upvotes Anonymous 1 User 0

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:
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.
Was this helpful?



Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License