Skip to main content

Closure

@serverSerrverlesskiy

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⚙️.

Snake

Requirements for creating a closure:

  1. An external function that is called in the code.
  2. The outer function contains the inner function.
  3. As a result, the outer function returns the inner one.

Let's consider creating a closure using an example:

Live Editor
Result
Loading...
  1. In the example, we have created an external function getFruit;
  2. Inside getFruit created an internal function show.
  3. The getFruit function returns the show function as a result.
  4. Further in the code, we assigned the result of the getFruit function to the variable showFruit.
  5. Because the result of getFruit is a function, then showFruit becomes not a variable, but a function.
  6. 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.

Examples of

Math

Let's look at more examples for understanding.

Counter

A counter is the simplest example to consider how a closure works.

Live Editor
Result
Loading...

Improved counter

Counter

As a result, we will have not one function⚙️, but several at once.

Live Editor
Result
Loading...

Closure in a loop

circle

Live Editor
Result
Loading...

Remember the phrase

l

Live Editor
Result
Loading...

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.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

What is a closure?

  1. Construction
  2. Function
  3. Concept

What is closure on what?

  1. Function on scope
  2. Variables in a function

What do you need to do to access a closed variable?

  1. I will describe it and use it
  2. It is available
  3. 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.

EnglishMoji!

  1. Learn JavaScript
  2. MDN Web Docs
  3. Замыкания JavaScript

Contributors ✨

Thanks goes to these wonderful people (emoji key):


IIo3iTiv


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨