According to me:
Closure is something that js creates separately to simulate the surrounding variables as if the function was being run as a normally called function so that we can pass functions as arguments etc.
What I mean by normally? ..when a function is executed in situations where an external environment is not required.
I have a piece of code that uses closure:
var x=1;
var f= function()
{
var a={result:0}
if(x==2)
a={result:1};
return function g ()
{
console.log(a.result);
}
}
returned=f()
x=2;
returned();
var arr=[1,2,3];
var f= function()
{
return function g ()
{
console.log(arr);
}
}
var returned=f();
arr=[4,5,6];
returned();
In what situations a closure is used instead of the lexical scope variable?