Horror Clouser In Javascript

mahin678

Mahin Tazuar

Posted on December 27, 2021

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:

đź’– đź’Ş đź™… đźš©
mahin678
Mahin Tazuar

Posted on December 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related