Closures in JS
Intoduction :-
The closure is a function together with a reference to the surrounding state, the lexical environment. Said another way, a closure gives access to the outer function's scope from an inner function. In JavaScript, closures are created every time a function is created—at function creation time.
The closure is a function together with a reference to the surrounding state, the lexical environment. Said another way, a closure gives access to the outer function's scope from an inner function. In JavaScript, closures are created every time a function is created—at function creation time.
//JS closures
const OuterFunction =()=>{
let postedBy="React-Native Developer Community" // local variable created by outer function
const InnerFunction=()=>{
//InnerFunction is the inner function, that forms the closure
let printMsg="Post by " + postedBy // local variable created by inner function,here used postedBy variable declared in the parent function
return printMsg
}
return InnerFunction()
}
const msg= OuterFunction()
console.log(msg)
OuterFunction() declares a local variable postedBy and a function InnerFunction(). That is, InnerFunction() is a function within a function. It is declared within the function OuterFunction() and is not accessible from any place other than the body of the OuterFunction() function. Now, the InnerFunction() function declares a local variable, printMsg, and makes use of the postedBy variable declared by OuterFunction(). However, inner functions have access to variables of the outer functions; therefore, InnerFunction() can make use of the variable postedBy declared in the parent function OuterFunction().
Comments
Post a Comment