is this function a closure in javascript? - javascript

function f1(){
var n=999;
function f2(){
alert(n); // 999
}
}
is the function f2() a closure? if not? why?
but in this post. How do JavaScript closures work?
why it says:
function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp));
}
bar(10);
}
foo(2)
That is not a closure.A closure is when you return the inner function. The inner function will close-over the variables of foo before leaving. why?
but i don't know what's the difference between the example i made and another i cited, one is not a closure.but one is. i think the two example is the same.

Yes, f2 is a closure, since it accesses a variable (n) from an outer scope. (OK, it's not really a closure -- see update below).
n was declared inside f1, not f2; this makes it belong to f1's scope. So when you create the function f2 which references n, it is a closure by definition, since it uses someone else's variable.
UPDATE
Alright, if I understand the answer you've linked to correctly, it says that f2 is not a closure because it is merely accessing a variable within its scope (just like an if statement, which gets its own scope within the braces*, can use variables from the outer scope without needing a closure).
* Update: Turns out that only functions get their own scope in Javascript, not any old blocks. But my point still stands...
However, f2 would become a closure if it left f1's scope (e.g. by being returned); in that case, it would still have access to f1's variable n, even though f1's original scope would no longer exist (it's exited when control leaves the function). f2 would have "closed over" f1's variables, thus artificially extending the lifespan of f1's scope.
Personally, I would still call f2 a closure, even if it never leaves f1. If a function can become a closure simply by being used outside of its declaring scope, and its behaviour inside that scope is no different whether it's technically a closure or not, then I see no point in making a distinction. I would even go so far as to say that it's an implementation detail whether f2 is a closure or not, if it never leaves f1's scope.
On the other hand, ignoring that distinction would mean that any function that uses a global variable would be called a "closure", since it accesses a variable from an outer scope. So the fact that it becomes a closure only when it leaves the scope(s) that the variables it is using are defined in is a worthwhile (albeit subtle) distinction.
I guess the clearest answer I can give is that it's not a closure yet.

It is a closure, because it depends on the values of variables in an intermediate (i.e. not local or global) scope, and if the variable changes then so will the operation of the closure. That the value is always the same is incidental.
You may however want to return the closure to the caller of f1() so that it can be used elsewhere.

Related

IIFEs as closures

In the You Don't Know Javascript series, 1/3 of the way down IIFE's are described as not being closures themselves, but only if they're executed outside their lexical scope:
Chapter 3 introduced the IIFE pattern. While it is often said that
IIFE (alone) is an example of observed closure, I would somewhat
disagree, by our definition above.
This code "works", but it's not strictly an observation of closure.
Why? Because the function (which we named "IIFE" here) is not executed
outside its lexical scope. It's still invoked right there in the same
scope as it was declared (the enclosing/global scope that also holds
a). a is found via normal lexical scope look-up, not really via
closure.
var a = 2;
(function IIFE(){ // not actually a "closure"
console.log( a );
})();
In this SO post, the following snippet was given as an example of a closure:
for (var i = 0; i < someVar.length; i++)
(function (i) {
window.setTimeout(function () {
alert("Value of i was "+i+" when this timer was set" )
}, 10000);
})(i);
I am trying to understand this in terms of the definition of closure (as defined in this medium article):
To use a closure, simply define a function inside another function and
expose it. To expose a function, return it or pass it to another
function. ...
The inner function will have access to the variables in the outer
function scope, even after the outer function has returned.
I understand that a closure is a "stateful function", and that it is
a way to "remember" and continue to access a function's scope (its
variables) even once the function has finished running.
So in this example, I see that the loop's i is remembered when passed into the closing IIFE.
My question is:
Where is the "passing to another function or returning" portion happening? My guess is that the IIFE is able to remember the outer i for loop value at each iteration because the IIFE is passed to the window?
Basically, my understanding is that a closure is defined as remembering an outer scope's value after the Garbage collector cleans that outer scope up, and that the usage of it is to expose the closure by returning it and accessing it outside its lexical scope. Is this correct? So where is that "accessing it outside the lexical scope" happening?
in this example, I see that the loop's i is remembered when passed into the closing IIFE
No. The IIFE is only providing the scope for the i value to be remembered. As the quotes you cited state, the IIFE function is not a closure. The function expression that uses the i is the closure:
(function IIFE(i) {
// this is the scope of i
window.setTimeout(function closure() {
// this function closes over i
alert("Value of my local 'i' is still "+i+" even after 10 seconds");
}, 10000);
})(0);
// ^ this is some arbitrary value passed to the IIFE - it could have been a loop variable
Where is the "passing to another function or returning" portion happening?
It's the closure function being passed into setTimeout, which will call it back from a place where i would usually be no longer defined - if it wasn't a closure.

Bind a changing variable in function, I want a name

I have somethings like:
var i = 0;
var func = function(){
console.log(i);
};
func(); //0
i++;
func(); //1
I want to have the second console also output '0',
so I change the program like:
var i = 0;
var func = (function(_i){
return function(){
console.log(_i);
};
})(i);
func(); //0
i++;
func(); //0
I know how it works, but is there any name or terms to describe such mechanism?
I've been calling this mechanism "breaking the closure" though I've had arguments in the past with people who insist on calling this technique "closure".
The reason I call it "breaking" closures is because that's what you're doing.
The classic place where you see this is in solutions for closures in loops:
var hellos = [];
for (var i=0; i < 10; i++) {
hellos.push(
(function(j){
return 'hello ' + j
})(i)
);
}
The problem is caused by a closure being created between the outer variable and references to that variable in the inner function (technically the variable is called a "free" variable rather than a closure, "closure" technically refers to the mechanism that captures the variable but in the js community we've ended up calling both things closures). So closure is the cause of the problem. Since the problem is caused by a closure being created I've started referring to the solution as "breaking the closure".
Note that even though some people call this a closure and you may google for "js closure" to read more about this technique it is ironically not a closure. What it is is simply how functions pass arguments (there's a whole side-argument about how javascript actually pass arguments to functions which you can read here: Why are objects' values captured inside function calls?). Javascript is a fairly strict pass-by-value language in the same way C is a strict pass-by-value language (C can ONLY pass by value).
When you pass a reference in js (objects, arrays) the function will not get the original reference but rather a copy of the reference. Since it is a reference it obviously points to the same object as the original reference so it is easy to mistakenly believe that javascript passes by reference. But if you try to assign a new object to the passed-in reference you will notice that the original reference does not change. For example:
function foo (x) {
x = [2,3];
}
var y = [1,2];
foo(y);
console.log(y) // prints [1,2] so foo() did not change y
It is this mechanism that is responsible for breaking the association between the outer variable (in your example that would be i) and the inner variable (_i in your example). The name of this mechanism is simply function calling (well, technically it is a subset of function calling - it is how arguments are passed to function calls).
So to recap:
I personally call it "breaking the closure"
Some people call it "closure" even though it is not a closure (the closure is what they want to avoid instead).
Side note: I realize that the original example is about a global variable but in javascript global variables are just a special case of closures - closures are ALWAYS created when you define a function, it's just that when there's no outer function the outer scope is simply the global scope.
It's called a closure. You can read more about them here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.
if the variable in the scope is not declared, it will search the outer scope, until find it, or to the window scope. if not find, it will the variable global.

Is it possible to Detect Closure Programmatically?

I have a function which allows user to pass a function.
function withPredicate(func){
//...
}
Inside my function, I need to detect whether the func that user pass in has closure or not.
It is not enough to get the function name and search it in window scope. User might pass in an anonymous function without closure like:
var func = function(x){return x;};
withPredicate(func);
EDIT:
I think I need to implement a function which takes a function as a argument and return bool.
function hasClosure(func){
//...
}
so several test cases are:
hasClosure(function(x){return x;}); //return false
var something = 30;
var func1 = function(x){return x.age < something;}
hasClosure(func1); //return false
var Closure = function(){
var something = 18;
var itself = function(x){
return x.age < something;
};
return itself;
};
var func2 = new Closure();
hasClosure(func2); //return true
The last one return true because func2 is not top-level function. When I see some free variable inside the function body like something, it may resolve to the variable defined in its closure other than the one defined in window.
Actually, what I need to do now is to do some manipulations based on the func that has been passed to my function. I can use JSLint to get the undeclared variable. But I also need to resolve these variables. It is acceptable that I can only resolve variables in global scope. But I still need a way to make sure that resolving these variables in global scope is correct. So I need to detect closures.
Is it possible to do that programmatically in javascript?
Alright this is really hacky and probably not worth the effort in actually writing unless your linting or something :)
Basically what you're going to have to do to determine if a function is a closure is call func.toString() which will give you the source of the function. You can then parse the function using some sort of parser which determines all the variables of the function func. You also need to determine and track how these variables are defined. In your criteria in op the criteria for it being a closure is having a variable that is defined outside of function scope and outside of window scope (thus closure scope). So if you can find any variables defined outside of these two scopes we've found a closure.
So heres the pseudocode of hasClosure(), have fun implementing.
func hasClosure(func)
source = func.toString(); //eg "function x(a) {return new Array(a)}"
variables = parseJSForVariables(source)//finds a and Array
for variable in variables:
if(variable not in window)
if(variable not defined in function)
return true //we got a closure
return false //not a closure
The correct answer highly depends on what a "closure" means in this context. The function from the question does not use the variables from the outer scope so, roughly, closure is not created for this function. But strictly speaking, closure is created for any function and binds definition context with the function. So whatever you want to detect, it requires a detailed specification.
But I can assume that the closure here means whether the function references variables declared in outer scope (just like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures specifies). One of the static for analysis libraries can be used for this. For example, JSLint reports used but undeclared variables. Assuming that undeclared variables are just from the upper scope, this indicates that closure is created.

javascript function internal scope [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Consider the following code:
function nepaliBuddha() {
var a = 20;
return function buddhaNepal() {
console.log(a);
}
}
var closure = nepaliBuddha();
closure(); // logs 20
Now when we invoke closure output is 20. This proves that the internal scope property ([[scope]]) was assigned to the inner function where it was defined or say when declared.If this wasn't assigned at declaration ,there was no way to log 20 as it gets invoked in different context
Invoking closure() the scope chain of a function context is created at function call and consists of the activation object or VO of the current context and the internal [[scope]] property of this function.
Invocation also creates [[scope]] property , this means that internal scope property is created at declaration as well as at execution isn't it?
Usually the definition says the [[scope]] property gets created at run time or at function call but this isn't true as [[scope]] property is already assigned at declaration as well.
What I think is the [[scope]] property might get updated after execution of function, is it? Please give clear definition of [[scope]] internal property. How and when it is created at declaration time or at execution time or at both time.
Wow, aren't you thoroughly confused. Alright, I'll try to explain closures as simply as possible.
First, we'll start with scopes. There are two types of scopes:
Block scopes
Function scopes
A block scope begins immediately when it occurs in the program. A function scope on the other hand does not begin until the function is called. Hence multiple calls to the same function result in multiple scopes being created.
JavaScript does not have block scopes. It only has function scopes. Hence to emulate a block scope we need to create a function expression and immediately execute it. This patttern is called an immediately invoked function expression (IIFE) and it looks like this:
(function () {
// this is the JS equivalent of a block scope
}());
Beside block scopes and function scopes there's another way to classify scopes. Hence we also have:
Lexical scopes
Dynamic scopes
This distinction only applies to function scopes because block scopes are always lexically scoped. JavaScript only has lexical scopes.
To understand the difference between lexical scopes and dynamic scopes we need to understand the difference between free and bound variables.
A free variable is a variable which is used within a function but which is not declared within that function.
A variable which is declared within a function is said to be bound to that function.
Consider the following program:
function add(x, y) {
return x + y; // x and y are bound to add
}
In the above program the variables x and y are bound to the function add because they are declared within add.
On the other hand the variables x and y in the following program are free within the function add because they are not declared within add but they are used within add:
function add() {
return x + y; // x and y are free within add
}
Now free variables are a problem. They need to be mapped to some value, but which value? This is where lexical and dynamic scopes come into picture. I won't go into the major details, but you can read about it on Wikipedia.
Scopes are a lot like prototypal inheritance. When a new scope begins it inherits from a parent scope forming a chain of scopes much like prototype chains in JavaScript.
Lexical scopes and dynamic scopes differ with respect to which parent scope a new scope inherits form.
In lexical scoping a new function scope inherits from the scope in which that function was defined (i.e. its lexical environment).
In dynamic scoping a new function scope inherits from the scope in which that function was called (i.e. the calling scope).
Since JavaScript only has lexical scoping we won't bother with dynamic scoping. Consider the following program:
var count = 0;
function incrementCount() {
return ++count;
}
(function () {
var count = 100;
alert(incrementCount()); // 1
}());
Here the function incrementCounter has one free variable - count. Since JavaScript has lexical scoping count will be mapped to the global variable count instead of the local count declared within the IIFE. Hence incrementCount returns 1 and not 101.
Now closures only work in languages which have lexical scoping. Consider the following program:
function getCounter() {
var count = 0;
return function () {
return ++count;
};
}
var counter = getCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
In the above program the function returned by getCounter is a closure with respect to the variable count because:
The variable count is free within the returned function (i.e. counter).
The function is moved outside of the scope within which count is declared.
Both these conditions are necessary for a function to be called a closure. For more information read the following answer: https://stackoverflow.com/a/12931785/783743
Now the important thing to understand here is that the function counter will still be called a closure even though it may never be invoked. A closure is simply a function which closes over a variable (which is called the upvalue of the closure).
When we invoke getCounter we create a new scope (let's call this scope A), and each time we invoke the function returned by getCounter (i.e. counter) we create a new scope which inherits from scope A. That's all. No new closure is created.
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
Now call makeFunc()
var myFunc = makeFunc();
myFunc();
In this case, myFunc is a closure that incorporates both the displayName function and the "Mozilla" string that existed when the closure was created, MDN.
So, the scope created exactly when I called var myFunc = makeFunc(); and myFunc() (the result of the makeFunc() call) is now a closure. So, go to the first line where
A closure is a special kind of object that combines two things: a
function, and the environment in which that function was created.
Now consider these
function nepaliBuddha() {
var a = 1;
return function buddhaNepal() {
a = a+1;
console.log(a);
}
}
var closure1 = nepaliBuddha(); // An individual scope
var closure2 = nepaliBuddha(); // An individual scope
closure1(); // 1
closure1(); // 2
closure2(); // 1
closure2(); // 2
closure2(); // 3
Demo.
Which means, closure1() and closure2() are closures and both have their personal scope/environment and they have access to their own scope once they get it (in this case, every time you call nepaliBuddha you are creating a closure and giving/saving it to a variable).
Scope defines the area, where functions, variables and such are available. So, when you defined/declared the function buddhaNepal (inner function) inside the nepaliBuddha (outer function) the buddhaNepal (inner function) has been just separated from the global scope and nothing else. It can't access anything in the global scope but it has it's own scope, that's it. The nepaliBuddha (outer function) is the boundary of the buddhaNepal (inner function) and in this case the nepaliBuddha outer function's local scope/environment is the global scope for the buddhaNepal (inner function).
in JavaScript, this is known as Lexical Scopeing it defines how variable names are resolved in nested functions. Other names of Lexical Scope are Static Scoping or Closure. It means that the scope of an inner function contains the scope of a parent function.

Javascript Closures (Object literal Vs Constructor based)

When using Javascript Closures, is there some difference in using Object literal Vs Constructor based objects ?
Are there just syntax difference OR is there some other difference as well for Closures?
Any example explaining the 2 differences would be really helpful.
Closures are a feature of functional programming. They have nothing to do with objects or object literals.
Read the following answer - it explains closures really well: https://stackoverflow.com/a/12931785/783743
In general a closure is a function which closes over the variables in a nested function which moves out of the scope of the closure. For example:
function getCounter() {
var count = 0;
return function counter() {
return ++count;
};
}
var counter = getCounter();
counter(); // 1
counter(); // 2
counter(); // 3
Here the function getCounter becomes a closure because it closes over the variable count used in the nested function counter when the nested function is returned (moves out of the scope of getCounter).
The variable which is closed over (in this case count) is called an upvalue. Closures are important because they allow values which would otherwise go out of scope (be garbage collected) to remain alive. This is not possible in languages like C/C++ and Java.
Closure is more about the function scope of the variable. So the important thing to know is that the scope of a variable is the function it was defined in. Any function that run inside this scope will have access to its parent function per se. Parent function won't have access to a child function variable, because it's outside of that child's scope.
Therefore a variable in an object literal, would be scoped to the function that it is contained it. (If it's not in a function, then it's in the global scope). A constructor is a function so any variables that it defines, is scoped in itself and inaccessible outside. Any inner methods that are in the constructor has access to those defined variables.
Closures are created when a function has access to a variable that is outside its own scope and that variable may be changed or altered by something else...even well after the function has finished execution.
I hope that helped some what.

Categories