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 isBedroom()
andOfficeRoom()
.The
Fridge()
function bundled together with reference to its surrounding state that isoven
. And everything it has referenced fromHome()
.The
Penguin()
function bundled together with reference to its surrounding state that isbread
. And everything it has referenced fromFridge()
.
In hierarchy it will bundle reference to function until Global scope.
Now we have three closure, and let see what chrome dev tool says.
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
Top comments (0)