The Wayback Machine - https://web.archive.org/web/20231027233912/https://www.geeksforgeeks.org/what-is-the-self-executing-function/
Open In App
Related Articles

What is the Self-Executing Function ?

Improve Article
Improve
Save Article
Save
Like Article
Like

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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 02 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials