What is closure in Javascript? What is the need of closure in js? Where is it good to use practically? I went through some articles but could not able to understand the actual use of closure in js. Explain with examples so that i will understand the concept of closure in a better way.
Share
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
Look at the example below:
Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object’s properties) with one or more methods.
Links that can help you to understand:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Closure is similar to lexical environment/scope… Outer/parent function ko variables chai inner/child function le access garna paunxa…. And also … inner function lai return gari sake paxi pani… Memory maa /closure maa tyo variable chai rahi rakhxa…note:- return gari sake paxi… Outer Function ko environment sakinxa…. But still inner function maa chai tyo variable access garna sakxau outer function ko…. Tesai lai closure vanxa….
Eg:- euta outerFuction create gara…tesma 2/3 ota variable banau …ani innerFuction create gara…. inner function lai direct call na gari… Return gardeu ….
return innerFuction. ..like this
And outerFuction vanda bairaw do ..
let inner = outerFuction()
console.dir(inner) gara…tesma closure vannw scope hunxa…tya outer function ko variables vetxau…. That means … Even tho you have returned inner function inside outer function… Still that inner function has access variables of that outer function…
Hope you understood it… If anydoubt …dm me
Practical use ko case chai yesto ho… function declaration garey paxi… Closure aafai create hunxa…. So..its a concept you should know… Always asked in interviews…
Timle aile samma unknowingly closure chai use gari rakhe ko xau… Just know the concept about closure thats enough
You would love to check this
https://www.facebook.com/groups/itsnporg/posts/1163712074410221/
this might be helpful
In nesting functions, even after the outer function has completed its execution, the inner function can access the variables of the outer/parent function. For eg:
function outer(){
let counter=0;
function inner(){
counter ++;
console.log(counter)
}
return inner
}
const count = outer()
count()
count()
The output will be 1 and 2. Here even after the outer function has been executed, the value of Counter (this variable is defined in the outer function) is remembered in the inner function. Hope it helped.