Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 20, 2021 05:36 pm GMT

Easiest way to understand Javascript Closure

Closure is one most discussed topics in javascript for many reasons, but I am going to make it simple to understand. First we will look at the definition of Closure from MDN.

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state

Let break it down with the most familiar example.

--Home --Bedroom --Office Room --Kitchen  --Fridge   --Penguin

Let look at the above structure, A home, and inside it a Bedroom, an Office room since its 2021, and Kitchen. Also, there is a Fridge inside the kitchen. Now consider there is a penguin in the fridge, yay yay they came back due to global warming.

function Home() { function OfficeRoom(){  console.log('OfficeRoom') } function Bedroom(){  var bed = "bed"  console.log('Bedroom') } function Kitchen() {  var oven = "oven"  function Fridge() {   var bread = "bread"   function Penguin() {    console.log(bread, oven, Bedroom(), OfficeRoom())   }   Penguin()  }  Fridge() } Kitchen()}Home()

what Penguin() function can access?

The above is what I converted in javascript code. Let see what penguin has access to

  • Everything in fridge
  • Everything in Kitchen
  • Everything in Home

Let go from the top, can penguin access the office room, in real-world it can access and may fix some of your bugs, But in the javascript world, it can only call OfficeRoom() since its a function and it can return anything, same goes for Bedroom().

Moving to Kitchen() it can access oven variable and in Fridge() it can access bread variable.

Now let's look at the definition of closure

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state

  • The Kitchen() function bundled together with reference to its surrounding state that is Bedroom() and OfficeRoom().

  • The Fridge() function bundled together with reference to its surrounding state that is oven. And everything it has referenced from Home().

  • The Penguin() function bundled together with reference to its surrounding state that is bread. And everything it has referenced from Fridge().

In hierarchy it will bundle reference to function until Global scope.

Now we have three closure, and let see what chrome dev tool says.

Debugger screenshot

Every function that bundled together with references to its surrounding state is closure. In fact, closure is created every time a function is created.

For more read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures


Original Link: https://dev.to/khalid283/easiest-way-to-understand-javascript-closure-7ol

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