What is a Closure?
A closure is a function having access to the parent scope, even after the parent function has closed. Closures in JavaScript is a feature where an inner function has access to the outer function's variables.
A closure has three scope chains
- Has access to its own scope [the variable defined within it's curly]
- Has access to the variables of the outer functions
- Has access to the global variables
var a = 10;
function first_func(){
var b = 20;
function second_func(){
var c = a+b;
return c;
}
return second_func();
}
var sum = first_func();
document.write("The sum is " + sum + '<br>')
function temporary(){
let counter = 0;
return function(){
counter +=1;
}
}
const add = temporary();
console.dir(add)
add();
function temporary(){
let counter = 0;
return function(){
// counter +=1;
console.log("Death Closure")
}
}
const add = temporary();
console.dir(add)
add();
Top comments (0)