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:
SyntaxError: Unexpected token (1:8) 1 : return () ^
- 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.
Thanks goes to these wonderful people (emoji key):
🐛 🎨 🖋
🖋 🐛 🎨