How do JavaScript closures work?

Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike

How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?

by (550 points) | 403 views

1 Answer

0 like 0 dislike

Two brief summaries

  • When a function (foo) declares other functions (bar and baz), the family of local variables created in foo is not destroyed when the function exits. The variables merely become invisible to the outside world. foo can therefore cunningly return the functions bar and baz, and they can continue to read, write and communicate with each other through this closed-off family of variables ("the closure") that nobody else can meddle with, not even someone who calls foo again in future.

  • A closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.

by (1.2k points)

Related questions

0 like 0 dislike
6 answers
asked Apr 3, 2019 by Z_Coder
0 like 0 dislike
7 answers
0 like 0 dislike
2 answers
0 like 0 dislike
7 answers
asked May 21, 2019 by yankoyski
0 like 0 dislike
1 answer
asked Apr 26, 2019 by LemanRass21
110,608 questions
257,187 answers
40,163 users