Excerpt: There are several concepts in JavaScript that you should be familiar with if you work with web development on a regular basis. Some of you may find it absolutely necessary, while others may find it only marginally useful in your project. As we’re already discussing JavaScript concepts, let’s take a closer look at one more concept called closure in JavaScript. Closures in JavaScript must be one of those concepts that a lot of people have trouble grasping.

Introduction: 

Closures JavaScript will be discussed in this article. We’ll go over the definition of a closure, an example of a simple day-to-day retrieve utility closure, and some of the benefits and drawbacks of using closures. Closures are indeed a key concept in JavaScript that help programmers write better code. Typically, they are antagonised by developers who haven’t used them in years and believe that if they haven’t needed them up to this point, they can live without them.

What are exactly mean by closures?

A closure is a function that has been grouped together (enclosed) with citations to its environment (the lexical environment). In other words, we can coin the termed closures as Closures are functions that do have access to variables in their scope chain even though the outer function is no longer active. However to know better insights on  Programming & Frameworks Courses definitely JavaScript Training plays an important role.

There are three scope chains within closure:

  1. It has access to variables defined among its curly brackets, which it can use.
  2. It has full rights to the variables of the outer function.
  3. It is able to access global variables.

Before we get started, let’s define the terms scope and lexical scope. Then, once you’ve mastered the fundamentals, you’ll only need to take one more step to grasp closures.

  • The Scope:

You would like a variable to exist inside some constraints when you define it. A result variable, for example, makes sense to have as an internal detail within a calculate() function. The result variable is absolutely worthless outside of calculation ().

Variable accessibility is controlled by scope. You can access the variable defined inside its scope at any time. However, the variable is unreachable outside of that scope.

A function or a code block in JavaScript creates a scope.

Let’s look at how the scope affects the variable count’s availability. This variable is part of the scope created by the foo() function:

Inside the scope of foo, the count can be accessed at any time ().

However, the count is unavailable outside of the foo() scope. In any case, if you try to access count from the outside, JavaScript will throw a ReferenceError: count is not defined.

If you define a variable inside of a function or code block, you can only use it inside of that function or code block. This is demonstrated in the preceding example.

Let’s look at an example of a general formulation:

  • The scope is just a space policy that governs variable accessibility.
  • The scope isolates variables, which is an immediate property. This is useful because variables with much the same name can exist in different scopes.
  • Without colliding, you can reuse common variable names (count, index, current, value, and so on) across scopes.
  • The count variables in the foo() and bar() function scopes are different but named the same:
scope2.jpg
  • Scopes nesting:

Let’s play around with scopes a little more and nest one into another. For example, the innerFunc() function is nested inside the outerFunc() function ().

What would be the relationship between the two function scopes? Is it possible to access the outerFunc() variable outerVar from inside scope of innerFunc()?

scope nesting.jpg

Within the scope of innerFunc(), the outerVar variable is accessible. The outer scope’s variables are accessible from the inner scope.

nested.jpg

You now know two fascinating facts:

  1. Scopes can also be nested to create more scopes.
  2. The outer scope’s variables are accessible from within the inner scope.
  • The Lexical Scope:

How does JavaScript know that the variable outerVar of innerFunc() is the same as the variable outerVar of outerFunc()?

Lexical scoping is a scoping mechanism implemented by JavaScript (or static scoping). The accessibility of variables is determined by their position within the nested scopes, which is known as lexical scoping.

To put it another way, lexical scoping implies that variables from other scopes can be accessed from within the inner scope.

It’s called lexical (or static) since the engine determines the nesting of scopes (at the lexing time) without executing the JavaScript source code.

“The lexical scope is composed of outer scopes that are statically determined.”lexical scope.jpg

  • innerOfInnerOfFunc(lexical )’s scope is made up of innerOfFunc(), func(), and global scopes (the outermost scope). You could perhaps access the lexical scope variables myInnerVar, myVar, and myGlobal from within innerOfInnerOfFunc().
  • innerFunc() has two lexical scopes: func() and global scope. The lexical scope variables myVar and myGlobal can be accessed from within innerOfFunc().
  • Finally, the global scope is the only lexical scope of func(). The lexical scope variable myGlobal can be accessed from within func().

But, exactly, what is closure?

  • A Simple closure:

Let’s consider the example of a simple closure in JavaScript:

simple closure.jpg

There are two functions here:

  1. an outer function external with such a variable b that returns the inner
  2. function inner with a variable called a that accesses an outer variable b inside its function body.

Variable b’s search was restricted to the outer function, while variable a’s scope is limited to the inner function.

Let’s call the outer() function and save the result in a variable called X. Let’s call the outer() function again and save the result in variable Y.

outer.jpg

Let’s take a look at what is happening when the outer() function is called for the first time:

  1. The value of variable b is set to 10, and its scope is limited to the outer() function.
  2. There is nothing to execute after the next line, which is a function declaration.
  3. Return inner looks for a variable called inner on the last line, determines that this variable inner is a function, and returns the entire body of the function inner.
  4. [Note that the return statement returns the entire body of the function rather than executing the inner function — a function is only executed when it is followed by () —.]
  5. The contents of the return statement are saved in the variable X.

As a result, X will save the following information:

outer2.jpg

The function outer() has completed its execution, and all variables inside the scope of outer() have vanished.

This final section is crucial to comprehend. Any variables defined inside the function scope vanish once the function has completed its execution.

The Closure:

Okay, the lexical scope allows you to access the variables of the outer scopes statically. There’s only one more step until the end!

Let’s look at the outerFunc() and innerFunc() examples once more:

closure.jpg

The variable outerVar is made accessible from the lexical scope inside the innerFunc() scope. That is already known.

InnerFunc() is called within the scope of its lexical scope (the scope of outerFunc()).

Let’s make some changes: innerFunc() can now be used outside of its lexical scope, for example, in a function exec (). Is it still possible for innerFunc() to access outerVar?

Make the following changes to the code snippet:

closeur 2.jpg
  • InnerFunc() is now implemented outside of its lexical scope but within the exec() function’s scope. What’s more, here’s what’s crucial:
  • Even when executed outside of its lexical scope, innerFunc() has access to outerVar from its lexical scope.

In those other worlds, innerFunc() removes the variable outerVar from its lexical scope (a.k.a. captures, remembers).

In other words, innerFunc() is a closure, so it closes the lexical scope of the variable outerVar.

closure 3.jpg

The closure, to put it another way, is a function that recalls the variables from wherever it is defined, irrespective of where it is performed later.

A rule of thumb for identifying a closure is that if you see an alien variable (not defined within that function) inside a function, it’s most likely a closure since the alien variable is captured.

outerVar is an alien variable within the closure innerFunc() captured from the scope of outerFunc() in the previous code snippet.

Let’s look at some more examples of why the closure would be useful.

Closure Examples:

  1. Event Handler
  2. Callbacks
  3. Functional programming
  • Event Handler:
evenet handler.jpg

To use the demo, open it and click the button. The number of clicks is updated in the text.

handleClick() is called somewhere within the DOM code when the button is clicked. The execution takes place in a different location than the definition.

Because handleClick() is a closure, it captures countClicked from the lexical scope and updates it when a click occurs. Furthermore, myText is also captured.

  • Callbacks:

In callbacks, trying to capture variables from lexical scope is useful.

A callback for setTimeout():

callbacks.jpg

Since it tries to capture the countEven variable, the iterator is a closure.

  • Functional programming:

Whenever a function returns another function until all of the arguments have been supplied, this is known as currying.

func prog.jpg

Multiply is a curry function that returns another curry function.

Closures make currying, an important concept in functional programming, possible.

The closure executeMultiply(b) captures a from its lexical scope. The captured variable a and the parameter b are used to calculate a * b when the closure is called.

Benefits of Closure:

  1. Variables can be attached to an execution context using them.
  2. Closure variables can help you keep track of a state that you can use later.
  3. They are used to encapsulate data.
  4. They assist in the removal of redundant code.
  5. They aid in the maintenance of modular code.

Drawbacks of Closure:

  1. Garbage collection does not apply to variables declared within a closure.
  2. A large number of closures can cause your application to slow down. Duplication of code in memory is the root of the problem.

Remarks at the End

Closures are one of the more difficult concepts in JavaScript to grasp at first. However, once you understand them, you realize that nothing could have gone any better. Finally, a closure is a variable-capturing lexical scope function. To put it another way, regardless of where it is executed, the closure remembers the variables from where it was defined. As a result, when dealing with or implementing certain design patterns, closures can be extremely useful. They can also help you write clean, modular code.

Author Bio:

I am Korra Shailaja, Working as a Digital Marketing professional & Content writer in MindMajix Online Training. I Have good experience in handling technical content writing and aspire to learn new things to grow professionally. I am an expert in delivering content on the market demanding technologies like Mulesoft Training, Dell Boomi Tutorial, Elasticsearch Course, Fortinet Course, PostgreSQL Training, Splunk, Success Factor, Denodo, etc.