How do you explain this structure in JavaScript? - javascript

(function()
{
//codehere
}
)();
What is special about this kind of syntax?
What does ()(); imply?

The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
function name (){...}
name();
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.

It's an anonymous function being called.
The purpose of that is to create a new scope from which local variables don't bleed out. For example:
var test = 1;
(function() {
var test = 2;
})();
test == 1 // true
One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.
The snippet below will cause an error:
var aVariable = 1
var myVariable = aVariable
(function() {/*...*/})()
Here's what it's actually doing:
var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();
Another way of creating a new block scope is to use the following syntax:
new function() {/*...*/}
The difference is that the former technique does not affect where the keyword "this" points to, whereas the second does.
Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.

That is a self executing anonymous function. The () at the end is actually calling the function.
A good book (I have read) that explains some usages of these types of syntax in Javascript is Object Oriented Javascript.

This usage is basically equivalent of a inner block in C. It prevents the variables defined inside the block to be visible outside. So it is a handy way of constructing a one off classes with private objects. Just don't forget return this; if you use it to build an object.
var Myobject=(function(){
var privatevalue=0;
function privatefunction()
{
}
this.publicvalue=1;
this.publicfunction=function()
{
privatevalue=1; //no worries about the execution context
}
return this;})(); //I tend to forget returning the instance
//if I don't write like this

See also Douglas Crockford's excellent "JavaScript: The Good Parts," available from O'Reilly, here:
http://oreilly.com/catalog/9780596517748/
... and on video at the YUIblog, here:
http://yuiblog.com/blog/2007/06/08/video-crockford-goodstuff/

The stuff in the first set of brackets evaluates to a function. The second set of brackets then execute this function. So if you have something that want to run automagically onload, this how you'd cause it to load and execute.

John Resig explains self-executing anonymous functions here.

Related

What is the point of a page load anonymous function? [duplicate]

In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
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);
This will first log 3 and then throw an error on the next console.log because foo is not defined.
Simplistic. So very normal looking, its almost comforting:
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?
Wait... what?
I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.
So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.
One problem: it has a function in it called 'name' same as my function.
This is what's called a collision. We've got two functions declared in the same scope with the same name. We want to avoid this.
So we need to scope our code somehow.
The only way to scope code in javascript is to wrap it in a function:
function main() {
// We are now in our own sound-proofed room and the
// character-converter library's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.
We have a function in a function... which is weird to look at, but totally legal.
Only one problem. Our code doesn't work.
Our userName variable is never echoed into the console!
We can solve this issue by adding a call to our function after our existing code block...
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
main();
Or before!
main();
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.
We need MORE scoping. And some way to automatically execute our main() function.
Now we come to auto-execution functions (or self-executing, self-running, whatever).
((){})();
The syntax is awkward as sin. However, it works.
When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.
So lets look at our code again, with some self-executing syntax:
(function main() {
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
)();
So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar.
After many years of professional development, I strongly urge you to name every function you write for debugging purposes.
When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!
Self-invocation (also known as
auto-invocation) is when a function
executes immediately upon its
definition. This is a core pattern and
serves as the foundation for many
other patterns of JavaScript
development.
I am a great fan :) of it because:
It keeps code to a minimum
It enforces separation of behavior from presentation
It provides a closure which prevents naming conflicts
Enormously – (Why you should say its good?)
It’s about defining and executing a function all at once.
You could have that self-executing function return a value and pass the function as a param to another function.
It’s good for encapsulation.
It’s also good for block scoping.
Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)
More here.
Namespacing. JavaScript's scopes are function-level.
I can't believe none of the answers mention implied globals.
The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/
Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.
The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)
As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":
Better namespace management (Avoiding Namespace Pollution -> JS Module)
Closures (Simulating Private Class Members, as known from OOP)
The first one has been explained very well. For the second one, please study following example:
var MyClosureObject = (function (){
var MyName = 'Michael Jackson RIP';
return {
getMyName: function () { return MyName;},
setMyName: function (name) { MyName = name}
}
}());
Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.
Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.
Let us try some experiments:
I can get MyName using getMyName and it works:
console.log(MyClosureObject.getMyName());
// Michael Jackson RIP
The following ingenuous approach would not work:
console.log(MyClosureObject.MyName);
// undefined
But I can set an another name and get the expected result:
MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.
Here's a solid example of how a self invoking anonymous function could be useful.
for( var i = 0; i < 10; i++ ) {
setTimeout(function(){
console.log(i)
})
}
Output: 10, 10, 10, 10, 10...
for( var i = 0; i < 10; i++ ) {
(function(num){
setTimeout(function(){
console.log(num)
})
})(i)
}
Output: 0, 1, 2, 3, 4...
Short answer is : to prevent pollution of the Global (or higher) scope.
IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.
This is the other way to write IIFE expression. I personally prefer this following method:
void function() {
console.log('boo!');
// expected output: "boo!"
}();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
First you must visit MDN IIFE , Now some points about this
this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
Self executing function are used to manage the scope of a Variable.
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 and can be accessed from anywhere within the script, 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, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
var localvar = "localvar"; //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
(function(){
var foo = {
name: 'bob'
};
console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error
Actually, the above function will be treated as function expression without a name.
The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.
The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.
Given your simple question: "In javascript, when would you want to use this:..."
I like #ken_browning and #sean_holding's answers, but here's another use-case that I don't see mentioned:
let red_tree = new Node(10);
(async function () {
for (let i = 0; i < 1000; i++) {
await red_tree.insert(i);
}
})();
console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
where Node.insert is some asynchronous action.
I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
You can use this function to return values :
var Test = (function (){
const alternative = function(){ return 'Error Get Function '},
methods = {
GetName: alternative,
GetAge:alternative
}
// If the condition is not met, the default text will be returned
// replace to 55 < 44
if( 55 > 44){
// Function one
methods.GetName = function (name) {
return name;
};
// Function Two
methods.GetAge = function (age) {
return age;
};
}
return methods;
}());
// Call
console.log( Test.GetName("Yehia") );
console.log( Test.GetAge(66) );
Use of this methodology is for closures. Read this link for more about closures.
IIRC it allows you to create private properties and methods.

Are javascript IIFE's only about namespacing? [duplicate]

In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
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);
This will first log 3 and then throw an error on the next console.log because foo is not defined.
Simplistic. So very normal looking, its almost comforting:
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?
Wait... what?
I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.
So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.
One problem: it has a function in it called 'name' same as my function.
This is what's called a collision. We've got two functions declared in the same scope with the same name. We want to avoid this.
So we need to scope our code somehow.
The only way to scope code in javascript is to wrap it in a function:
function main() {
// We are now in our own sound-proofed room and the
// character-converter library's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.
We have a function in a function... which is weird to look at, but totally legal.
Only one problem. Our code doesn't work.
Our userName variable is never echoed into the console!
We can solve this issue by adding a call to our function after our existing code block...
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
main();
Or before!
main();
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.
We need MORE scoping. And some way to automatically execute our main() function.
Now we come to auto-execution functions (or self-executing, self-running, whatever).
((){})();
The syntax is awkward as sin. However, it works.
When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.
So lets look at our code again, with some self-executing syntax:
(function main() {
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
)();
So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar.
After many years of professional development, I strongly urge you to name every function you write for debugging purposes.
When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!
Self-invocation (also known as
auto-invocation) is when a function
executes immediately upon its
definition. This is a core pattern and
serves as the foundation for many
other patterns of JavaScript
development.
I am a great fan :) of it because:
It keeps code to a minimum
It enforces separation of behavior from presentation
It provides a closure which prevents naming conflicts
Enormously – (Why you should say its good?)
It’s about defining and executing a function all at once.
You could have that self-executing function return a value and pass the function as a param to another function.
It’s good for encapsulation.
It’s also good for block scoping.
Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)
More here.
Namespacing. JavaScript's scopes are function-level.
I can't believe none of the answers mention implied globals.
The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/
Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.
The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)
As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":
Better namespace management (Avoiding Namespace Pollution -> JS Module)
Closures (Simulating Private Class Members, as known from OOP)
The first one has been explained very well. For the second one, please study following example:
var MyClosureObject = (function (){
var MyName = 'Michael Jackson RIP';
return {
getMyName: function () { return MyName;},
setMyName: function (name) { MyName = name}
}
}());
Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.
Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.
Let us try some experiments:
I can get MyName using getMyName and it works:
console.log(MyClosureObject.getMyName());
// Michael Jackson RIP
The following ingenuous approach would not work:
console.log(MyClosureObject.MyName);
// undefined
But I can set an another name and get the expected result:
MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.
Here's a solid example of how a self invoking anonymous function could be useful.
for( var i = 0; i < 10; i++ ) {
setTimeout(function(){
console.log(i)
})
}
Output: 10, 10, 10, 10, 10...
for( var i = 0; i < 10; i++ ) {
(function(num){
setTimeout(function(){
console.log(num)
})
})(i)
}
Output: 0, 1, 2, 3, 4...
Short answer is : to prevent pollution of the Global (or higher) scope.
IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.
This is the other way to write IIFE expression. I personally prefer this following method:
void function() {
console.log('boo!');
// expected output: "boo!"
}();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
First you must visit MDN IIFE , Now some points about this
this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
Self executing function are used to manage the scope of a Variable.
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 and can be accessed from anywhere within the script, 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, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
var localvar = "localvar"; //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
(function(){
var foo = {
name: 'bob'
};
console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error
Actually, the above function will be treated as function expression without a name.
The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.
The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.
Given your simple question: "In javascript, when would you want to use this:..."
I like #ken_browning and #sean_holding's answers, but here's another use-case that I don't see mentioned:
let red_tree = new Node(10);
(async function () {
for (let i = 0; i < 1000; i++) {
await red_tree.insert(i);
}
})();
console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
where Node.insert is some asynchronous action.
I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
You can use this function to return values :
var Test = (function (){
const alternative = function(){ return 'Error Get Function '},
methods = {
GetName: alternative,
GetAge:alternative
}
// If the condition is not met, the default text will be returned
// replace to 55 < 44
if( 55 > 44){
// Function one
methods.GetName = function (name) {
return name;
};
// Function Two
methods.GetAge = function (age) {
return age;
};
}
return methods;
}());
// Call
console.log( Test.GetName("Yehia") );
console.log( Test.GetAge(66) );
Use of this methodology is for closures. Read this link for more about closures.
IIRC it allows you to create private properties and methods.

Should I put my entire Javasscript script inside a self invoking function? [duplicate]

In javascript, when would you want to use this:
(function(){
//Bunch of code...
})();
over this:
//Bunch of code...
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);
This will first log 3 and then throw an error on the next console.log because foo is not defined.
Simplistic. So very normal looking, its almost comforting:
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?
Wait... what?
I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.
So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.
One problem: it has a function in it called 'name' same as my function.
This is what's called a collision. We've got two functions declared in the same scope with the same name. We want to avoid this.
So we need to scope our code somehow.
The only way to scope code in javascript is to wrap it in a function:
function main() {
// We are now in our own sound-proofed room and the
// character-converter library's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.
We have a function in a function... which is weird to look at, but totally legal.
Only one problem. Our code doesn't work.
Our userName variable is never echoed into the console!
We can solve this issue by adding a call to our function after our existing code block...
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
main();
Or before!
main();
function main() {
// We are now in our own sound-proofed room and the
// character-converter libarary's name() function can exist at the
// same time as ours.
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.
We need MORE scoping. And some way to automatically execute our main() function.
Now we come to auto-execution functions (or self-executing, self-running, whatever).
((){})();
The syntax is awkward as sin. However, it works.
When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.
So lets look at our code again, with some self-executing syntax:
(function main() {
var userName = "Sean";
console.log(name());
function name() {
return userName;
}
}
)();
So, in most tutorials you read, you will now be bombarded with the term 'anonymous self-executing' or something similar.
After many years of professional development, I strongly urge you to name every function you write for debugging purposes.
When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!
Self-invocation (also known as
auto-invocation) is when a function
executes immediately upon its
definition. This is a core pattern and
serves as the foundation for many
other patterns of JavaScript
development.
I am a great fan :) of it because:
It keeps code to a minimum
It enforces separation of behavior from presentation
It provides a closure which prevents naming conflicts
Enormously – (Why you should say its good?)
It’s about defining and executing a function all at once.
You could have that self-executing function return a value and pass the function as a param to another function.
It’s good for encapsulation.
It’s also good for block scoping.
Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)
More here.
Namespacing. JavaScript's scopes are function-level.
I can't believe none of the answers mention implied globals.
The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/
Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.
The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)
As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":
Better namespace management (Avoiding Namespace Pollution -> JS Module)
Closures (Simulating Private Class Members, as known from OOP)
The first one has been explained very well. For the second one, please study following example:
var MyClosureObject = (function (){
var MyName = 'Michael Jackson RIP';
return {
getMyName: function () { return MyName;},
setMyName: function (name) { MyName = name}
}
}());
Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.
Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.
Let us try some experiments:
I can get MyName using getMyName and it works:
console.log(MyClosureObject.getMyName());
// Michael Jackson RIP
The following ingenuous approach would not work:
console.log(MyClosureObject.MyName);
// undefined
But I can set an another name and get the expected result:
MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.
Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.
Of course, on half the JS implementations out there, they will anyway.
Is there a parameter and the "Bunch of code" returns a function?
var a = function(x) { return function() { document.write(x); } }(something);
Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.
Here's a solid example of how a self invoking anonymous function could be useful.
for( var i = 0; i < 10; i++ ) {
setTimeout(function(){
console.log(i)
})
}
Output: 10, 10, 10, 10, 10...
for( var i = 0; i < 10; i++ ) {
(function(num){
setTimeout(function(){
console.log(num)
})
})(i)
}
Output: 0, 1, 2, 3, 4...
Short answer is : to prevent pollution of the Global (or higher) scope.
IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.
This is the other way to write IIFE expression. I personally prefer this following method:
void function() {
console.log('boo!');
// expected output: "boo!"
}();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
First you must visit MDN IIFE , Now some points about this
this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
Self executing function are used to manage the scope of a Variable.
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 and can be accessed from anywhere within the script, 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, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
var localvar = "localvar"; //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.
Since functions in Javascript are first-class object, by defining it that way, it effectively defines a "class" much like C++ or C#.
That function can define local variables, and have functions within it. The internal functions (effectively instance methods) will have access to the local variables (effectively instance variables), but they will be isolated from the rest of the script.
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
(function(){
var foo = {
name: 'bob'
};
console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error
Actually, the above function will be treated as function expression without a name.
The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.
The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.
Given your simple question: "In javascript, when would you want to use this:..."
I like #ken_browning and #sean_holding's answers, but here's another use-case that I don't see mentioned:
let red_tree = new Node(10);
(async function () {
for (let i = 0; i < 1000; i++) {
await red_tree.insert(i);
}
})();
console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
where Node.insert is some asynchronous action.
I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
You can use this function to return values :
var Test = (function (){
const alternative = function(){ return 'Error Get Function '},
methods = {
GetName: alternative,
GetAge:alternative
}
// If the condition is not met, the default text will be returned
// replace to 55 < 44
if( 55 > 44){
// Function one
methods.GetName = function (name) {
return name;
};
// Function Two
methods.GetAge = function (age) {
return age;
};
}
return methods;
}());
// Call
console.log( Test.GetName("Yehia") );
console.log( Test.GetAge(66) );
Use of this methodology is for closures. Read this link for more about closures.
IIRC it allows you to create private properties and methods.

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

Javascript function change variables scope

I am attempting to declare a function outside of anonymous function but still have acess to all of the anonymous functions variables
Below is demonstrating what I'm talking about.
I just need to get rid of eval.
//Used to determine where the variable is being stored
var variableScope = "global";
(function(window){
var variableScope = 'insideFunction',
appearingToBeGlobalFunction = function(){
alert("This Function appears Global but really isn't");
};
window["addFunction"]=function(funName,fun){
//window[funName] = fun; Doesn't work
eval("window[funName]="+fun+";");
}
})(window);
addFunction("alertTest",function(){
alert(variableScope);
appearingToBeGlobalFunction();
});
//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();
Edit: The goal of this question was to ultimately keep the global scope clean from tons of variables, but still have the convenience of accessing, set and calling as if they were global. I have concluded there is a way to doing what I'm after but it requires a deprecated functionality in javascript.
Here is some example code showing how to accomplish the above without eval.
This article discusses how to use "with".
var variableScope = "global";
var customScope = {
variableScope : 'insideFunction',
appearingToBeGlobalFunction : function(){
alert("This Function appears Global but really isn't");
}
};
function alertTest(){
with(customScope){
alert(variableScope);
appearingToBeGlobalFunction();
}
};
//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();​
You can't get rid of eval and still expect it to work. That's the only way to take a look at members of the scope after it's been "closed." I've messed around with something similar in the past, but I would never actually use it anywhere. Consider an alternate solution to whatever you're trying to accomplish.
eval("window[funName]="+fun+";");
Oh dear Lord.
The reason this “works” is that you are converting the function fun (alertTest) into a string to put it in the eval argument.
It happens that in most desktop browsers, a native JS function's toString() result will be a string that looks like a function expression containing the same code as the original declaration. You're turning a function back into a string and re-parsing that string in the context of the new enclosing function, so the new function value is the same code but with a different closure.
However, it is not required that Function#toString work like this, and in some cases it won't. It is not safe to rely on function decomposition; avoid.
You can certainly only do this kind of horrific hackery using eval, although there is no reason the window[funName]= part has to be inside the eval. window[funName]= eval('('+fun+')'); would work equally well (badly).
I am attempting to declare a function outside of anonymous function but still have acess to all of the anonymous functions variables
Whyever would you do something crazy like that?
you could force the variables to be in the global scope eg instead of var variableScope = 'insideFunction' you use window.variableScope = 'insideFunction'
The goal of this question was to ultimately keep the global scope clean from tons of variables, but still have the convenience of accessing, set and calling as if they were global. I have concluded there is a way to doing what I'm after but it requires a deprecated functionality in javascript.
Here is some example code showing how to accomplish the above without eval.
This article discusses how to use "with".
var variableScope = "global";
var customScope = {
variableScope : 'insideFunction',
appearingToBeGlobalFunction : function(){
alert("This Function appears Global but really isn't");
}
};
function alertTest(){
with(customScope){
alert(variableScope);
appearingToBeGlobalFunction();
}
};
//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();​

Categories

Resources