Skip to content

Self-invoking function JavaScript | Example code

Self-invoking function is not really 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 basically the same:

var f = function(){...}; f()

and

( function(){...} )()

Self-invoking function JavaScript

Simple example of self-executing function.

<!DOCTYPE html>
<html>
<body>
  <script>

    (function () {
      console.log("Self-invoking functions")
    }());

  </script>
</body>
</html> 

Output:

Self-invoking function JavaScript

Self invoking function vs regular function

A “self-invoking function” is a name for a common JavaScript idiom. It’s not actually 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. Variables declared in the self executing function are, by default, 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.

Soruce: stackoverflow.com/

Do comment if you have any doubt 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

1 thought on “Self-invoking function JavaScript | Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *