Open In App

What is the Self-Executing Function ?

Last Updated : 02 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A self-executing function is a function in JavaScript that doesn’t need to be called for its execution it executes itself as soon as it is created in the JavaScript file. This function does not have a name and is also called an anonymous function. This function is initialized inside a set of round brackets and the parameters can be passed through the round brackets at the end.

Syntax:

(function (parameters) {
    // Code block to be executed
})(parameters);

Example:

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
        
    <b>
        What is a self-executive function?
    </b>
        
    <p>
        This page was generated on: 
        <span class="output"></span>
    </p>
  
        
    <script type="text/javascript">
        (function () {
            date = new Date().toString();
                
            document.querySelector('.output').textContent
                        = date;
        })();
    </script>
</body>
    
</html>


Output:

Naming anonymous functions: We can assign a name to a self-executing function with the following syntax. This can be used to call the function in the future.

Syntax:

(function_name = function (parameters) {
    // Code block to be executed
})(parameters);

Example:

Javascript




(print_name = function (name = "Geek") {
    console.log("The function is executed by " + name);
})();
  
print_name("GFG");


Output:

The function is executed by Geek
The function is executed by GFG

Why should we use a self-executing function?

One of the advantages that we get from a self-executing function is that the variables inside a self-executing function are not accessible outside of the function. This prevents global space to be filled with an extra variable that is not needed and takes up extra space. We can see in the following example the variable created inside the self-executive function is not accessible outside it and results in an error.

Example:

Javascript




(print_name = function () {
    let name = "Geek";
    console.log("The function is executed by " + name);
})();
  
console.log(name);


Output: This will throw an error as the name variable is not defined in the global space.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads