Last Updated : 25 Nov, 2024
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) {JavaScript
// Code block to be executed
})(parameters);
(function () {
date = new Date().toString();
console.log(date);
})();
Mon Nov 25 2024 17:15:50 GMT+0000 (Coordinated Universal Time)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) {JavaScript
// Code block to be executed
})(parameters);
(print_name = function (name = "Geek") {
console.log("The function is executed by " + name);
})();
print_name("GFG");
The function is executed by Geek The function is executed by GFGWhy 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.
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4