This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?
Related
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 6 years ago.
Is there any benefit for the following JavaScript module defenition:
var module = (function(){
var PublicFnc = function(){ // variable declaration
alert('hi');
}
return {
f : PublicFnc
}
})();
module.f();
Over the following:
var module = (function(){
function PublicFnc(){ // function declaration
alert('hi');
}
return {
f : PublicFnc
}
})();
module.f();
Although the second example is more convenient since it is more similar to Java/C# the anonymous methods are used more often and I'm wondering what is the benefit?
#Alexander, thanks for marking the question as duplicate but I tend to leave it open since I'm asking for the benefits within the context of module patterns and not generally
One of the differences between them can be explained using a concept called hoisting
In case:
a(); //you cannot call this function before its definition as here var a is undefined
var a = function(){ //function statement
console.log("Hello World");
}
a(); //this will call the function even before its definition because of hoisting
function a(){ //function definition
console.log("Hello World");
}
Also some the function in the above case is assigned a memory space using that variable.
In hoisting, function definition is hoisted and not the function statement.
Read more about hoisting here http://www.w3schools.com/js/js_hoisting.asp
Also, when to use statement and when to use definition depends on use case and personal preference
This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok
When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!
To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.
This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Can someone explain what the difference is between these closures? Is there a difference? I haven't previously seen the second example (parentheses inside).
(function(a, b) {
//...
})(x, y);
// Parentheses inside
(function(a, b) {
//...
}(x, y));
And here, is there a difference between these closures? Is there a scenario where there would be a difference?
FOO.Bar = (function() {
//...
})();
FOO.Bar = (function() {
//...
}());
No. In both cases they are exactly the same.
What happens when you wrap your function in parentheses is that is goes from a function declaration to a function expression, which can be invoked immediately.
Whether you invoke it within the parentheses or after does not matter. The "convension" has happened and you can thus invoke it.
And actually you can do this
FOO.Bar = function () {
return 123;
}();
The above is already a function expression since you are assigning an anonymous function to a property Bar on FOO.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?
What is the difference between the two ways to declare a function in JavaScript?
myFunction : function(variable)
{
}
or
function myFunction(variable)
{
}
Your first code snippet is not valid - it only works within an object; example:
var object = {
myFunction: function(variable) { }
};
// object.myFunction();
Basically there are two ways to define a function ins JavaScript:
function myFunction(variable) { }
var myFunction = function(variable) { };
The difference is: The first type of declaration uses the function statement and therefore allows you to use the function before it has been declared. Example:
console.log(myFunction()); // prints test
function myFunction(variable) { return "test"; }
Read more about it here.
This is not possible with the second type of function declaration, which assigns an anonymous function to a variable. The function can't be used before the variable has been declared.
One is a method. The other a function.
Functions are defined
function myfunction() {..}
Methods are defined
myobject.mymethod = function() {...} ;
A method is a property of an object that points to / is a function of that object
Really it depends on how you structure your objects. Functions are usually used in global libraries that are non object specific while methods are tied to objects to execute specific pieces of functionality.