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
getFruitcreated an internal function
- The getFruit function returns the show function as a result.
- Further in the code, we assigned the result of the
getFruitfunction to the variable
- Because the result of
getFruitis a function, then
showFruitbecomes not a variable🔔, but a function.
- The result of the whole construction is the variable
fruit, which is inside the function
getFruit, it became closed. Now we can only find out the value of this variable🔔, we cannot change it.
Let's look at more examples for understanding.
A counter is the simplest example to consider how a closure works.
As a result, we will have not one function⚙️, but several at once.
Closure in a loop
Remember the phrase
Write to Discord chat.
What is a closure?
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.
Thanks goes to these wonderful people (emoji key):
🐛 🎨 🖋
🖋 🐛 🎨