Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2021 04:23 pm GMT

Closure Explained!

Let's Define Closure

A closure is a function that makes use of variable defined in outer functions that have previously returned. What does this mean, Let's quickly look at an example.

function outer(a){    return function inner(b){        return a + b;    }}outer(5)(5); // 10

In the above code snippet, the function inner uses the variable "a" declared in a function named "outer," and when the function inner is called, the function outer returns the function called "inner," and thisis called as a closure!

A few things to note:

  • We have to 'return' the inner function for the above example to work.
  • We can call the inner function right away by using an extra ().
  • We don't have to name the inner function (we just called it "inner" for learning purposes)

How Closures Work

Only variables used in the inner function are stored!
Closures don't remember everything from an outer function - just the variables they require!

Why do I need to know this?

Private Variables

Variables that cannot be updated externally are supported in other languages. These are referred to as private variables, although they are not included in JavaScript. No need to be concerned - closures can assist!

function counter(){    let count = 0;    return function(){        count++;        return count;    }}
const counter1 = counter();counter1(); // 1counter1(); // 2const counter2 = counter();counter2(); // 1counter2(); // 2counter1(); // 3 this is unaffected by counter2.console.log(count); // Uncaught ReferenceError: count is not defined - because it is private!

TL;DR

  • Closure exists when an inner function makes use of variables declared in an outer function that has previously returned.
  • Closure does not exist if you do not return an inner function and if that inner function does not make use of variables returned by an outer function.
  • JavaScript will only remember values that are being used inside of the inner function, not all variables defined in the outer function.
  • Closures allow us to define private variables and write cleaner code that separates our logic from our application.

Thank you for making it till the end!


Original Link: https://dev.to/duhbhavesh/closure-explained-2di3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To