[JavaScript] Self-Executing Anonymous Functions

The main building block of JavaScript is a function. Unlike other languages, a function is very versatile in JavaScript. For example, a function is also an object too. The concept of an anonymous function is very simple but anonymous functions are used in many JavaScript patterns.

 

1. Anonymous Function

An anonymous function is a function without a name.

function () {
  console.log("Anonymous Function");
}

The first question might be “How can we execute the function that does not have a name?”

 

2. Function as an Object

In JavaScript, a function is an object so you can use a variable to refer to it.

var myFunc = function () {
  console.log("Anonymous Function");
}

myFunc();

Note the syntax to execute a function through a variable. The variable is like a function name.

(myFunc)();

This syntax is interesting. You can wrap the variable with parentheses; it is perfectly legal.

 

3. Self-Executing Anonymous Functions

What if you replace the variable with a function definition?

(function () {
  console.log("Anonymous Function");
})();

The function is declared and is executed right away. It is called a “Self-Executing Anonymous Function“.

 

4. What for?

Self-executing anonymous functions can be executed only once because there is no reference to it. So what is the purpose of it?

A self-executing anonymous function is also used to create a module, which I will explain in the subsequent post.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s