This question already has answers here:
What is this practice called in JavaScript?
(7 answers)
Closed 8 years ago.
(function() {
//do stuff
})();
EDIT: I originally thought this construct was called a closure - not that the effect that it caused results (potentially) in a closure - if variables are captured.
This is in no way to do with the behaviour of closures themselves - this I understand fully and was not what was being asked.
It is an anonymous function (or more accurately a scoped anonymous function) that gets executed immediately.
The use of one is that any variables and functions that are declared in it are scoped to that function and are therefore hidden from any global context (so you gain encapsulation and information hiding).
it's an anonymous function but it's not a closure since you have no references to the outer scope
http://www.jibbering.com/faq/notes/closures/
I usually call it something like "the immediate invocation of an anonymous function."
Or, more simply, "function self-invocation."
Kindof. It's doesn't really close around anything though, and it's called immediately, so it's really just an anonymous function.
Take this code:
function foo() {
var a = 42;
return function () {
return a;
}
}
var bar = foo();
var zab = bar();
alert(zab);
Here the function returned by foo() is a closure. It closes around the a variable. Even though a would apear to have long gone out of scope, invoking the closure by calling it still returns the value.
No, a closure is rather something along these lines:
function outer()
{
var variables_local_to_outer;
function inner()
{
// do stuff using variables_local_to_outer
}
return inner;
}
var closure = outer();
the closure retains a reference to the variables local to the function that returned it.
Edit: You can of course create a closure using anonymous functions:
var closure = (function(){
var data_private_to_the_closure;
return function() {
// do stuff with data_private_to_the_closure
}
})();
Related
This question already has answers here:
Is it true that every function in JavaScript is a closure?
(2 answers)
Closed 3 years ago.
I have been reading a fair bit about closures in JS.
I have been through various guides as this one https://medium.freecodecamp.org/javascript-closures-simplified-d0d23fa06ba4
I still have one question though. Does a closure only refere to first order function (function returning a function). Or, is any function a closure ?
The only difference I see really is like with some function not nested, one of the 3 scope chain (outer function's scope) would be empty still it doesn't exist.
A closure is created by calling a function; the function itself isn't the closure. Conceptually, every function call implicitly causes a new closure to come into existence. For some functions, the closure is ephemeral and just vanishes as soon as the function returns:
function add2(n) {
return n + 2;
}
That function returns only a number; nothing can refer to anything in the closure created by the function call, so the closure goes away and all you have left is the return value.
The closure becomes interesting when a function returns something that has one or more "hooks" into the local environment created when the function was called. (The function can expose the closure by modifying the global environment too.) So this function:
function addn(addend) {
return function(n) {
return n + addend;
}
}
exposes the closure because the returned function has a reference to the parameter of the outer function.
I can't think of a way an ordinary function can expose a closure that doesn't somehow involve one or more functions that reference stuff from the local context (parameters, variables). (Generator functions are interesting, because yield kind-of always returns something that exposes the closure, I suppose.)
A closure is the combination of a function and the lexical environment within which that function was declared
for example,
function greet(Say){
return (
function(name){
console.log(Say + ' ' + name);
}
)
}
Now I'm I can do something like this,
greet('Hi')('Alex')
This line will return the string 'Hi Alex'
Now I'm going to do something like this,
var sayGreet = greet('Hi');
If I console.log(sayGreet) it will be a function.
Now tell me where is this sayGreet variable defined? It is on the global level. Or in the other word global execution context.
Now let's do,
sayGreet('Alex')
inside this sayGreet function, we have a console.log(Say + " " + name) . We know name is Alex but what about Say? There is no sign of Say at this moment because the greet function already completed execution and returned a function.
Even though javascript still have the ability to refer to the Say value. Even it is completed the execution. This Say value can only be access by inner functions or nested functions.
This is call closure. A single function cannot be closure. There should be an outer lexical environment too.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Function declaration - Function Expression - Scope
I've learned about var a = 1, is defining a local variable, but talk about function, I thought It's only available within the current scope as the var variable behave, what's the difference between the following two code snippet?
function aPrint() {
console.log('a');
}
var a = function aPrent() {
console.log('a');
}
Your first example is a "function declaration". It declares a function that will be available anywhere in the scope in which it is declared (so you can call it before it appears in the source code). This is sometimes known as "hoisting" (as in, it gets hoisted to the top of its scope).
Your second example is a "named function expression". The variable declaration is hoisted to the top of the scope in which it is defined (like a function declaration) but the assignment still happens where you expect it to, so you can't call the function until after it has been assigned to the variable.
There is a third option, which is just a "function expression", where the function does not have a name (it's an anonymous function):
var a = function() {
console.log('a');
}
You will probably find that you have little use for named function expressions (although it can be useful when debugging), so it's usually better to use the anonymous function. In a named function expression, the name is only in scope inside the function itself, so you can't refer to the function by name normally.
here is a best article that may help you.
refer http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
function aPrint() {}
Declares a function (but does not execute it).
It will usually have some code between the curly brackets.
var a = aPrint()
Declares a variable, invokes a function (aPrint) and sets the value of aPrint to the return of the function.
var a= new aPrint()
Creates a new instance of an object based on the aPrint function. So the variable is now an Object, not just a string or a number.
Objects can contain indexed strings, numbers and even functions, and you can add more stuff to them, they're pretty awesome. The whole concept of Object Oriented Programming (OOP) is based on this.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the (function() { } )() construct in JavaScript?
I came across this bit of JavaScript code, but I have no idea what to make out of it. Why do I get "1" when I run this code? What is this strange little appendix of (1) and why is the function wrapped in parentheses?
(function(x){
delete x;
return x;
})(1);
There are a few things going on here. First is the immediately invoked function expression (IIFE) pattern:
(function() {
// Some code
})();
This provides a way to execute some JavaScript code in its own scope. It's usually used so that any variables created within the function won't affect the global scope. You could use this instead:
function foo() {
// Some code
}
foo();
But this requires giving a name to the function, which is not always necessary. Using a named function also means at some future point the function could be called again which might not be desirable. By using an anonymous function in this manner you ensure it's only executed once.
This syntax is invalid:
function() {
// Some code
}();
Because you have to wrap the function in parentheses in order to make it parse as an expression. More information is here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
So to recap quickly on the IIFE pattern:
(function() {
// Some code
})();
Allows 'some code' to be executed immediately, as if it was just written inline, but also within its own scope so as not to affect the global namespace (and thus potentially interfere with or be interfered with by, other scripts).
You can pass arguments to your function just as you would a normal function, for example,
(function(x) {
// Some code
})(1);
So we're passing the value '1' as the first argument to the function, which receives it as a locally scoped variable, named x.
Secondly, you have the guts of the function code itself:
delete x;
return x;
The delete operator will remove properties from objects. It doesn't delete variables. So;
var foo = {'bar':4, 'baz':5};
delete foo.bar;
console.log(foo);
Results in this being logged:
{'baz':5}
Whereas,
var foo = 4;
delete foo;
console.log(foo);
will log the value 4, because foo is a variable not a property and so it can't be deleted.
Many people assume that delete can delete variables, because of the way autoglobals work. If you assign to a variable without declaring it first, it will not actually become a variable, but a property on the global object:
bar = 4; // Note the lack of 'var'. Bad practice! Don't ever do this!
delete bar;
console.log(bar); // Error - bar is not defined.
This time the delete works, because you're not deleting a variable, but a property on the global object. In effect, the previous snippet is equivalent to this:
window.bar = 4;
delete window.bar;
console.log(window.bar);
And now you can see how it's analogous to the foo object example and not the foo variable example.
It means you created an anonymous function, and call it with parameter 1.
It is just the same as:
function foo(x) {
delete x;
return x;
}
foo(1);
The reason that you still get 1 returned is that the delete keyword is for removing properties of objects. The rest is as others have commented, anything wrapped in brackets executes as a function, and the second set of brackets are the arguments passed to that block.
Here's the MDN reference for delete, and the MDN reference for closures, which discusses also anonymous functions.
People normally call these "Immediately Invoked Function Expressions" or "Self Executing Functions".
The point of doing this is that variables declared inside that function do not leak to the outside.