DEV Community

Mahin Tazuar
Mahin Tazuar

Posted on

Horror Clouser In Javascript

Today we are talking about javascript closures. This is a very confusing topic and its most common interview question.

Before starting to learn this topic we need to good understand the Lexical scope and about some javascript garbage collection.

When we call a function inside another function and chield function can get Access his parent variable. this function can also modify this variable.

Garbage collection meaning in this page I want to explain about javascript ,when inside local scope we do not use a defined variable javascript move it his own garbage collection.Javacript have own detection sensitivity. Suppose when we are not using any semicolon javascript smartly understand and javascript fix that automatically. Javascript Smartly Handle it.

Now we are going about closures. When we define a function inside another function and we know this child function can get access to his parent function for lexical scope environment. Then we can update this variable which is defined parent function. Logically when we are called a function or leave a page, the inside function variable or page variable will die. Like we will not call this parent function, again and again, we just call one time the parent function and this function will be closed and we should not access this variable function. But Javascript understands that when in a lexical environment and after calling the parent function, javascript move the parent function variable inside a special environment or like temporary memory. And javascript fully gives access to this chield function.

function add(){
  let x = 0;
  return function(){
    return x= x+1;
  }
}
let f = add();
f();
f();
console.dir(f)// we can got 3 cz after calling chield function the varible value will saved in a clouser environment.
Enter fullscreen mode Exit fullscreen mode

Simple hints from - @lukeshiru
Just think about it as boxes, and the smaller box always has access to the things in the bigger one:

Top comments (2)

Collapse
 
mahin678 profile image
Mahin Tazuar

Thank you so much.Actully i am newbie and i will share my knowladge to writing the post. Its helps me understand about any topics.As a newbie i have not completed knowladge but i want to try minimum things which is give atlist a clear concept, Not everythings.

Collapse
 
suhakim profile image
sadiul hakim

Really Horror