Open In App

JavaScript – What is the Purpose of Self Executing Function?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The self-executing anonymous function is a special function which is invoked right after it is defined. There is no need to call this function anywhere in the script. This type of function has no name and hence it is called an anonymous function. The function has a trailing set of parentheses. The parameters for this function could be passed in the parenthesis. 

Syntax

(function (parameters) {
// Function body
})(arguments);
JavaScript
(function () {
    date = new Date().toString();

    console.log(date);
})();

Output
Mon Nov 25 2024 17:19:36 GMT+0000 (Coordinated Universal Time)

Why use an anonymous function? 

The advantage of using an anonymous function instead of writing code directly is that the variables and functions defined within the anonymous function are scoped locally and are not accessible outside of it. This helps prevent cluttering the global namespace with variables and functions that are not needed beyond the function’s scope. Anonymous functions can also be used to control access, allowing specific variables and functions to remain private while enabling access to others through closures.

Accessing a variable from outside the anonymous function

This example shows that accessing the date object from outside the anonymous function results in an error. 

JavaScript
(function () {
    let date = new Date().toString();

    console.log(date);
})();

console.log('The date accessed is: ' + date);

Output

 restrict-access 

Allowing access to one variable to outside the function

This example shows that the date variable could be made available outside the function by making it global. 

JavaScript
(function () {
    let date = new Date().toString();
    console.log(date);

    // Assign to global window making it
    // accessible to outside
    window.date = date;
})();

console.log('The date accessed is: ' + date);

Output

allow-access



Article Tags :

Similar Reads