What Is the Purpose of a Self Executing Function in JavaScript

What is the purpose of a self executing function in javascript?

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, as mentioned in a comment by Alexander:

(function() {

var foo = 3;

console.log(foo);

})();

console.log(foo);

Javascript - self-executing functions : why to use them if I can create local scope with not self-executing functions?

You usually wrap your functions in a anonymous function when you want to keep your scope contained. This is also part of the module pattern which is still pretty popular:

https://toddmotto.com/mastering-the-module-pattern/

Then you can assign the outcome of that IIFE to a variable so your scope can only be accessed by calling that variable.

myScope.myLocallyScopedProperty or myScope[myLocallyScopedProperty]

Your other function needs to be called manually and it also accessible from anywhere.

I suggest reading the article by Todd Moto it explains a lot.

what is self-executing anonymous function or what is this code doing?

Immediately invoked functions are typically used to create a local function scope that is private and cannot be accessed from the outside world and can define it's own local symbols without affecting the outside world. It's often a good practice, but in this particular case, I don't see that it creates any benefit other than a few more lines of code because it isn't used for anything.

This piece of code:

(function(exports){

exports.notGlobalFunction = function() {
console.log('I am not global');
};

}(module));

Would be identical to a piece of code without the immediate invocation like this:

module.notGlobalFunction = function() {
console.log('I am not global');
};

The one thing that is different is that in the first, an alias for modules called exports is created which is local to the immediately invoked function block. But, then nothing unique is done with the alias and the code could just as well have used modules directly.


The variable modules is created to be a single global parent object that can then hold many other global variables as properties. This is often called a "namespace". This is generally a good design pattern because it minimizes the number of top-level global variables that might conflict with other pieces of code used in the same project/page.

So rather than make multiple top level variables like this:

var x, y, z;

One could make a single top level variable like this:

var modules = {};

And, then attach all the other globals to it as properties:

modules.x = 5;
modules.y = 10;
modules.z = 0;

This way, while there are still multiple global variables, there is only one top-level global that might conflict with other pieces of code.


Similarly, an immediately invoked function creates a local, private scope where variables can be created that are local to that scope and cannot interfere with other pieces of code:

(function() {
var x, y, z;

// variables x, y and z are available to any code inside this immediately invoked function
// and they act like global variables inside this function block and
// there values will persist for the lifetime of the program
// But, they are not truly global and will not interfere with any other global
// variables and cannot be accessed by code outside this block.
// They create both privacy and isolation, yet work just as well

})();

Passing an argument into the immediately invoked function is just a way to pass a value into the immediately invoked function's scope that will have it's own local symbol:

(function(exports) {
// creates a local symbol in this function block called exports
// that is assigned an initial value of module
})(module);

Why are self-executing anonymous functions used in Javascript Module pattern?

How can a self-executing function hide private variables and only expose the returned object. Why does this not happen with a normal JavaScript function?

It does happen with normal JavaScript functions.

function MakeModule() {
var privateVariable = "foo",
privateMethod = function () {
alert('private method');
};

return {
PublicMethod: function () {
alert(privateVariable);
privateMethod();
}
};
}

var Module = MakeModule();

would work just fine.

The only difference is that the anonymous function introduces one less global variable and allows for itself to be garbage collected while MakeModule can't be collected unless explicitly deleted by the author.

Why using self executing function?

We use self executing function, to manage Variable Scope.

The scope of a variable is the region of your program in which it is defined.
A global variable has global scope; it is defined everywhere in your JavaScript code. (Even in your functions).
On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.

var scope = "global";
function checkscope() {
alert(scope);
}

checkscope(); // global

As you see, you can access the scope variable inside your function,
but, within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.

var scope = "global";
function checkscope() {
var scope = "local";
alert(scope);
}

checkscope(); // local
alert(scope); // global

As you see, variable inside the function, won't overwrite global variables.
Because of this feature, we put the code inside the self executing function,
to prevent overwriting the other variables, when our code get big and big.

// thousand line of codes
// written a year ago

// now you want to add some peice of code
// and you don't know what you have done in the past
// just put the new code in the self executing function
// and don't worry about your variable names

(function () {
var i = 'I';
var can = 'CAN';
var define = 'DEFINE';
var variables = 'VARIABLES';
var without = 'WITHOUT';
var worries = 'WORRIES';

var statement = [i, can, define, variables, without, worries];

alert(statement.join(' '));
// I CAN DEFINE VARIABLES WITHOUT WORRIES
}());
  • You can read more about JavaScript on this book: JavaScript: The Definitive Guide, 6th Edition.

Use of self-Invoking functions in JavaScript closures

Let's break this problem down into pieces :

(1)

 var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

first part is the self invoking anonymous function, this means that add will receive the result of execution of this function. Which in this case is nothing but the following anonymous function :

function () {return counter += 1;}   (2)

so this means that add will be a function !

Now the fun part is that inside the siaf (1) (self-invoking-anonymous function), we're declaring a counter variable, initialized to zero :

var counter = 0;

since counter belongs to the outer scope of (2), then (2) has access to it!

what JavaScript says, is that a function when created will capture its environment and persist it, so a closure (close over) is nothing but the combination of a function and its creation environment. That means that after return statement the add function which will now hold a reference to (2) will still have access to the counter variable which is initially set to 0;

so to increment the counter, we need increment (2), which means incrementing add like so :

add();

p.s : function created with Function constructor and returned in the same way as (2) won't capture the counter variable !!

Why Self-Executing Anonymous Functions

Your initial example isn't worth to be executed in an anonymous function, so its a bad example to understand WHY to use this technique. Here is a good example to explore state capturing:

var list = [{id: 1, data: null}, ...];

for (var i = 0; i < list.length; i++) {
(function(item) {
// start async request, for each item in the list, in the order of the list
asyncAjax("get-data-from-somewhere.json?what=" + list[i].id, function (response) {
// thats the on success callback, which gets executed when the server responded
// each item will have different response times, therefore the order of response is various
// if we would use simply list[i].data, it wouldn't work correctly, because "i" would has the value of list.length, because the iteration has been finished yet.
item.data = response;
});
})(list[i]); // the function will preserve the reference to the list item inside, until the function has been fully executed
}

When writing sync. code, you can always fallback to classic object oriented style of structering your code. So you can avoid closures / instant-anonymous function calls. But as soon as you use async. mechanics, closures get very handy and make your code looking more clean, off course only if you can read and understand closures :)

By the way, you could also simply write:

function(private) {}(outer)

is the same as

(function(private) {})(outer)

but the second is better, because its simply more obvious for the reader.

Javascript self calling function vs script tag placed directly after the HTML element

The self-executing function creates a new internal scope which contains the second variable and prevents it from leaking into the global namespace. The plain <script> block's first variable, however, will be added into the global scope.

Keep in mind that individual script blocks do not have their own scope, they all operate within the same global scope, which is necessary for scripts to interoperate.

What is the benefit of assigning a self executing anonymous function to a variable in javascript?

The main reason for this is namespacing variables. Functions introduce a new variable scope. In the case of the above example, timer is not clobbering the global namespace while still being available to the code that needs it.


Since I apparently need to clarify:

The goal is to have a variable outside the function:

var timer;

function delay() {
// use timer
}

Because if the variable would be inside the function, it would be reinitialized every time. We want a persistent value outside the function though.

In the above code timer is a global variable though. We don't want that. To avoid that, we close the variable up in a new scope so it's accessible to the delay function, but not globally:

var delay = (function () {
var timer;

return function () {
// use timer
};
})();

delay is now a function just as before which can use timer outside itself, yet timer is not in the global scope.



Related Topics



Leave a reply



Submit