3

I am relatively new to Javascript. I understand the concept of nested functions - but closures seem less clear. The similarity between the two (in my mind atleast), is confusing.

Could someone explain the difference? (preferrably, with some code snippet, to illustrate the points clearer).

Amit Jadhav
  • 43
  • 1
  • 3
  • Have you searched on SO? There are various questions that seem to provide answers that would help you: https://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions https://stackoverflow.com/questions/34615754/simple-closure-vs-closure-with-nested-function-return https://stackoverflow.com/questions/8967214/what-is-the-difference-between-a-closure-and-an-anonymous-function-in-js – e_i_pi Nov 09 '17 at 06:38

1 Answers1

6

One function written inside another function is called a nested function. Suppose that there are two functions outer function and inside it there is an inner function. The inner function will have access to its own variables, the outer functions variables, arguments and it has access to global variables. This is done by a scope chain. Every function so created has a scope chain associated with which helps us in accessing the variables value.

Now what are closures? Closures - the nested functions continue to live even when the outer function has completed is closure. The day to day way in which we are able to see closure is callbacks. Callbacks are functions which are usually executed when an event completes, when they are executed they have access to outer functions variables even though the outer function has completed its execution.

Dmitriy Buteiko
  • 624
  • 1
  • 6
  • 14