1.

What is the usage of onpagehide event in JavaScript?

Answer»

Closures are one of the most complex topic in JavaScript, but they are everywhere in JavaScript.

Closures are basically, the INNER function having access to the variables in the outer function SCOPE, even after the outer function has returned. To use a closure, simply define a function inside another function and expose it. To expose a function, RETURN it.

Consider the below code. The variable b have an scope in outer function i.e. from LINE 4 to line 10. So, at line 13 when we call the outer function, it can access the value of b, but at line 14 there is no outer function.

So, how does the innerFn() access the value of b. This is where the JS feature of Closures comes into play.

When the “var inner” is created at line 6, the JS engine not only STORES the function object information but also its scope information. So, it stores a scope of variable b inside the inner function object.

Now it doesn’t matter where you call inner, whether in this file or some third party file. It will always remember the value of a and b, as if a snapshot is been taken.

var a = 10;   function outer() {   var b = 20;      var inner = function() {     console.log(a);     console.log(b);   };   return inner; }   var innerFn = outer(); innerFn();  

Output

//10 //20


Discussion

No Comment Found