Introduction to JavaScript Self Invoking Functions
We have a lot of interesting features in JavaScript. One of it being Self Invoking functions. You might have not heard about this word but have used this feature in your daily programs. You might have not even known how to google it. This strange terminology of JavaScript would want you to get used to in daily software development. JavaScript Self invoking functions are nameless self-executing functions and invoked immediately after defining it. These self-invoking functions are man-made, these functions will execute automatically when followed by ( ). Without ( ), a function cannot be self-invoked.
Syntax
Below is the Syntax:
(function() {
// body of the function
})();
The pair of parentheses converts code inside parentheses into the expression:
function() { …. }
the second pair of parentheses continues the call to the function.
For e.g., below is an anonymous function, and its call:
(function(){
console.log("Look, this article is on self-invoking functions");
})();
This is similar to naming a function and calling it,
function sample() {
console.log("Look, this article is on self-invoking functions ");
}
sample();
Even though you might find slight variations here, the content of the function is the same and both variations are executed immediately. As soon the function is defined, it will be immediately invoked. This is useful in initialization, adding event listeners, etc. In jQuery, instead of using document. ready, a self-invoked function was used.
These functions are called as Immediately Invoked Function Expressions, as IIFE or Self Executing functions. The purpose of wrapping these functions is to control the visibility of its members. You might be thinking why we would ever need to use these self-invoking functions. So, let us dig deeper into it.
Why Self Invoking Functions Work?
In JavaScript, each function has its own scope. Take this, for example, variables defined using ‘var’ inside functions cannot be accessed outside. By surrounding the applications with anonymous functions, we create a scope around the function where variables declared are only accessible by that function. We can make the variables declared accessible outside the function but by default we don’t have this feature applicable to her. Let us have a look at some of the key points of JavaScript Self Invoking Functions.
- Execute only once and won’t let global namespace get piled up with crud which lasts for a lifetime.
- Convenient for executing initialization logics, we can perform initialization only once as we will lose the reference to function after execution.
- We have two syntax variations for Self-invoked functions as below,
Douglas Crockford’sJSLint:
(function () {
// body
}());
Alternative 'dog balls'
(function () {
// body
})();
- Parameters can also be passed to these Self invoked functions, generally, references to global objects are passed as parameters.
- Not too many arguments should be passed as functions become large and users need to scroll for the parameters.
- This Self Invoking function are mainly for variable scoping. By default, variables declared in self invoked functions are only available to code within the self-invoked function.
- Does not care about how variables are declared or named in another block of code in JavaScript.
Examples on JavaScript Self Invoking Functions
Below are the examples of JavaScript Self Invoking Functions:
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Nameless Functions that are invoked automatically</h2>
<p id="demo"></p>
<script>
(function () {
var sample = "Hi, Today we will see what is JavaScript Self Invoking Functions";
document.getElementById("demo").innerHTML = sample;
})();
</script>
</body>
</html>
Output:
Example #2
Anonymous function with Argument
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Nameless Functions with arguments that are invoked automatically</h2>
<p id="demo"></p>
<script>
(function(sample){
document.write(sample);
})("Lets connect together for a great learning at eduCBA");
</script>
</body>
</html>
Output:
Example #3
Difference between normal function and Self invoked function.
Code:
<!DOCTYPE html>
<html>
<head>
<title>
Let us see difference between a normal function and self invoked function
</title>
</head>
<body>
<h1 style="color: red">
Normal Function Vs Self Invoked Function
</h1>
<b>
Will be able to see the syntax difference here
</b>
<p>
Present Date and Time:
<span class="output"></span>
</p>
<script type="text/javascript">
(function () {
date = new Date().toString();
document.querySelector('.output').textContent
= date;
})();
function dateSample() {
date = new Date().toString();
document.write("Normal Function date here ", date);
}
dateSample();
</script>
</body>
</html>
Output:
Example #4
Code:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<h1 style="color: red">
Displaying Employer Name
</h1>
<p>
Name of the Employer:
</p>
<script type="text/javascript">
varemployeeName = "eduCBA";
(function (employerName) {
function display(employerName)
{
document.write("Employee works with: " + employerName);
}
display(employerName);
})(employeeName);
</script>
</body>
</html>
Output:
Advantages of Self Invoking Functions/Anonymous Functions
- As these functions are unnamed or anonymous, expression of the function is immediately invoked even without using any identifier or closure and not spoiling the scope.
- These anonymous functions are arguments passed to higher-order functions that needs to return a function. If the function is used only once, using a self Invoking function is easier as it is light weighted syntactically compared to the named function.
- These functions also accept arguments but not many arguments should be passed as it not recommended. Even the names of arguments being simpler, code would look complex and clumsy.
- Used for creating artificial namespace which do not exist in JavaScript.
- Mostly, a Modular pattern is implemented using self invoked functions where we keep the reference of functions’ object that is returned.
Conclusion
With this, we conclude our topic ‘JavaScript Self Invoking Functions’, We have seen what it means and how is it used in coding. Illustrated a few examples on how to use Anonymous function, and also have seen the difference between Named function and Anonymous/ Self Invoked functions. These functions can help us in creating a scope and prevent polluting global namespace. Also used to initialize values before the creation of objects. We have listed out a few advantages which will be helpful to get a brief overview on the feature. You people can still go and try various other methods of using these self Invoking functions.