Self-invoking function is not a part of JavaScript, it’s just a term that people are calling a specific pattern of code (like AJAX, etc.); these patterns should work anywhere that JavaScript works.
The “self-invoking function” is just creating an anonymous function and immediately calling it.
That is, the following are the same:
var f = function(){...}; f()
and
( function(){...} )()
Here’s a breakdown of the syntax:
- The function is defined inside a set of parentheses
(function() { /* code */ })
. - The entire function is wrapped in an additional set of parentheses
(...)
to create a function expression. - At the end of the function expression, there is an additional pair of parentheses
()
that immediately invokes (calls) the function.
Self-invoking function JavaScript
A simple example of a self-executing function.
<!DOCTYPE html>
<html>
<body>
<script>
(function () {
console.log("Self-invoking functions")
}());
</script>
</body>
</html>
Output:
Self-invoking function vs regular function
A “self-invoking function” is a name for a common JavaScript idiom. It’s not a type of function; it’s the immediate execution of a function. You can call it an IIFE for “immediately invoked function expression” instead if that helps.
(function () { // Anonymous function expression
// IIFE!
})(); // Invocation happens here with the ()!
var f = (function () { // Still anonymous
// Almost immediately invoked function expression!
});
f(); // Invocation happens here!
var f = (function f() { // Not anonymous – now called “f”
// Almost immediately invoked function expression!
});
f(); // Invocation happens here!
function f() { // Not anonymous
// Almost immediately invoked function *declaration* – not an expression!
}
f(); // Invocation happens here!
What is the purpose of a self-executing function in JavaScript?
Answer: It’s all about variable scoping. By default, variables declared in the self-executing function are only available to code within the self-executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.
For example:
(function() {
var foo = 3;
console.log(foo);
})();
console.log(foo);
This will first log 3
and then throw an error on the next console.log
because foo
is not defined.
Source: stackoverflow.com/
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
are you the guy how manage the linkedin page of Javascript