Self-Executing Function in JavaScript

Migel Hewage Nimesha Feb 15, 2024
  1. Self-Executing Function
  2. Methods to Create Self-Executing Functions
  3. Conclusion
Self-Executing Function in JavaScript

JavaScript is a programming language that most users around the world use for scripting. Usually, we use it along with HTML (HyperText Markup Language) and CSS (Cascading Styles Sheets) to have interactive and dynamic web content.

If you imagine a cake with three layers, JavaScript is the third layer, whereas HTML and CSS are the first and second layers. Without JavaScript, we only achieve web pages with static information.

By 2022, 98% of websites will have JavaScript on their client side, and we can do various activities using this remarkable scripting language.

The self-executing function is one of the essential features that JavaScript provides us. This article will examine a self-executing function, its uses, and how we can build it.

Self-Executing Function

In JavaScript, self-executing functions, also named self-invoking functions, execute when encountered in the script. The formal way we call self-executing functions is IIFE, also known as Immediately Invoked Function Expressions.

Why do we need self-executing functions? It’s because sometimes we might need to write code blocks that should not interfere with the rest of the code.

To overcome this issue, we can use self-executing functions.

Self-executing functions and codes inside them are contained within a function scope, so they do not conflict with other functions and variables.

Apart from that, self-executing functions have several advantages.

A self-executing function is beneficial when we need one-time executable functions or initialize tasks without calling them. Also, it is not necessary to define any global functions or variables.

Methods to Create Self-Executing Functions

Method 1: Anonymous Functions

Syntax:

(function(parameters) {
// statements
})(arguments);

This is the fundamental method to build a self-executing function. In the above way, the function is the keyword that defines the function and should be within the parentheses.

Putting the function inside the parenthesis is called wrapping the function. End of the parentheses, we should add another set of parentheses; then only it become a self-executing function.

We can set some parameters if we need to pass arguments to the function. Inside the curly brackets, we can type our code.

We can give arguments or leave them empty inside the outer parenthesis.

Let’s try this method with an example.

(function() {
let text = 'Hello world'
console.log(text)
})();

In the above code, we have declared a variable called text and assigned a string. Then we printed that variable using the console.log method.

Output:

log inside function

As you can see, our message has been displayed as we expected. Let’s add another console.log statement outside our function.

(function() {
let text = 'Hello world'
console.log(text)
})();
console.log(text);

Output:

log outside function

As in above, the console.log statement in the function will provide us with the expected output. But the one outside the function throws an error since the text is not a global variable.

Now let’s modify this code to give an argument to the function.

(function(text) {
console.log(text)
})('Hello world');

In the above code, we gave a string as the argument and assigned it to the text. Then inside the function, we printed the text, and the output met our expectations.

Output:

give argument

Method 2: Using a Function Name

Earlier, we discussed a method that did not use a function name. If we want to name our function, we can do it.

This method is very similar to the previous one, but we are only adding a function name, so it is not an anonymous function anymore.

Below is the syntax for the function.

(function functionName() {
  // statements
})();

As in the above syntax, we can set the function name after the function keyword. Then as we did earlier, we can add statements to the function.

Let’s try this method with the example. Also, we check whether the function impacts the console.log method that is outside the self-executing function.

(function exFunction() {
  let text = 'Hello world'
  console.log(text)
})();
console.log(text)

As in above, we have given exFunction as the name of our function. Here is the result.

use a function name

As you can see, the text variable gives us the string we expected, while the outer console.log function throws an error.

Method 3: Using the Asynchronous Function

Functions that deliver their results asynchronously are referred to as asynchronous functions. The syntax for defining an async function includes the keywords async and await.

It is also called the async-await function because of these two words. Await expressions simulate synchronous behavior by suspending the execution of promise-returning functions until a promise has been fulfilled or rejected.

We can build a self-executing function using the async function. The syntax is below.

(async function functionName() {
  // statements
})();

We should type the async function, so the compiler will know this is an async function. We can add a function name, but it is not mandatory.

Then within the curly brackets, we can type our code. Let’s try this method using the previous example.

(async function exFunction() {
  let text = 'Hello world'
  console.log(text)
})();

Here is the output we get after running the above code chunk.

asynchronous function

We get the same result as before.

Method 4: Using Arrow Syntax

This process is also similar to the above-discussed methods. But here, we use the arrow syntax for the function.

Through the arrow syntax, we can have a shorter function syntax. Below is the syntax for the self-executing function that has arrow syntax.

(() => {
     // Code to execute
 })();

As you can see, the function syntax has become very short. Try this method and add a console.log function after the self-executing function to see the impact.

(() => {
    let text = 'Hello world'
    console.log(text)
})();
    console.log(text)

For this example, we have not used a function name, and the result of this code is below.

arrow syntax

This method also gives us the same result as in the previous methods.

Conclusion

In this write-up, we had a brief introduction to JavaScript and discussed what a self-executing function is. There are more and more methods to build such a function, but mainly we discussed four methods.

To have a better understanding, we used some examples in each method.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - JavaScript Function