What is closure in JavaScript?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the local environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
JavaScript variables can belong to the local or global scope.Global variables can be made local (private) with closures.
Global VariablesA function can access all variables defined inside the function,
function myFunction() { let a = 4; return a * a;}
function myFunction() {
let a = 4;
return a * a;
}
But a function can also access variables defined outside the function,
let a = 4;function myFunction() { return a * a;}
In JavaScript, closures are created every time a function is created, at function creation time.
function makeFunc() { const name = "C-Sharpcorner"; function displayName() { console.log(name); } return displayName;}const myFunc = makeFunc();myFunc();
function makeFunc() {
const name = "C-Sharpcorner";
function displayName() {
console.log(name);
return displayName;
const myFunc = makeFunc();
myFunc();
..
Closure gives access to outer function scope from on inner function.Closure Function is combination of function bundles together(EnClosed) with refernce to its Surrounding State.Closure create every time the function is created,at function creation time.Ex:function init(){ var name =”Vijay”; function disp(){ console.log(“Closure Function Value is:” +name); } disp();}init();