Nested function can also access outer function variables and parameter and same for closure than what is exact diff between them?
-
1this QA on Javascript closures may be useful -> https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – Pitt Aug 21 '19 at 21:51
-
2Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jin Lee Aug 22 '19 at 00:38
1 Answers
A nested function is necessary to have a closure, but it isn't itself enough. There has to be a variable in the scope of the outer function that the inner function makes use of, and further there has to be a means by which the inner function can be called from somewhere not in the scope of the outer function. One simple way this can happen is by returning the inner function from the outer one:
function makeAdder(x) {
return function(y) {
return x + y;
}
}
var addOne = makeAdder(1);
var addTwo = makeAdder(2);
console.log(addOne(2));
console.log(addTwo(2));
Here, in this fairly trivial example, the inner function is said to "close" over the outer variable x
. Once makeAdder
has finished executing, the x
variable by the usual rules of scope should have been thrown away - but the value it had when makeAdder
was called is "remembered", in a sense, by the returned functions addOne
and addTwo
. This "remembering" of a variable is exactly what closure is.
Closure arises all over Javascript programs, often without the developer even necessarily being aware of it. Functions being passed as callbacks to other functions (eg. setTimeout
, event handlers, Ajax callbacks...) are a very common feature of the language, and all can naturally lead to closures being formed.
In every case, a nested function is there, as you can't have a closure without one - but a common-or-garden nested function, like:
function f() {
....
function g() {
}
....
}
does not necessarily lead to a closure. (At least, not as the term is usually used. Some would say that technically closure is still happening, but I don't think that use is helpful.) Closure only really arises in this example when the following two conditions also hold:
g
can be called from outside the scope off
- there is some variable in the scope of
f
whichg
accesses and/or alters
I highly recommend you read this for an excellent and detailed overview of what closures are and how they can be used.

- 17,805
- 2
- 23
- 34