Closure
A closure is a function⚙️ that has access to an external function⚙️ even after the external function️ has terminated. A closure is needed to provide an internal function with access to the scope of an external function️, but at the same time close access from the external environment to the variables of the internal function⚙️.
Requirements for creating a closure:
- An external function that is called in the code.
- The outer function contains the inner function.
- As a result, the outer function returns the inner one.
Let's consider creating a closure using an example:
- In the example, we have created an external function
getFruit
; - Inside
getFruit
created an internal functionshow
. - The getFruit function returns the show function as a result.
- Further in the code, we assigned the result of the
getFruit
function to the variableshowFruit
. - Because the result of
getFruit
is a function, thenshowFruit
becomes not a variable, but a function. - The result of the whole construction is the variable
fruit
, which is inside the functiongetFruit
, it became closed. Now we can only find out the value of this variable, we cannot change it.
Examples of
Let's look at more examples for understanding.
Counter
A counter is the simplest example to consider how a closure works.
Improved counter
As a result, we will have not one function⚙️, but several at once.
Closure in a loop
Remember the phrase
Total
Closures are one of the most important fundamental JavaScript concepts that every JS developer should understand. Understanding closures is one stepping stone to writing efficient, high-quality applications.
Problems?
Write to Discord chat.
Questions:
What is a closure?
- Construction
- Function
- Concept
What is closure on what?
- Function on scope
- Variables in a function
What do you need to do to access a closed variable?
- I will describe it and use it
- It is available
- The variable can only be viewed
In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.
Links
Contributors ✨
Thanks goes to these wonderful people (emoji key):
IIo3iTiv | Dmitriy Vasilev 💵 | Resoner2005 🐛 🎨 🖋 | Navernoss 🖋 🐛 🎨 |