Closure - Falicer/Project_Tech_2021 GitHub Wiki

coding dev

What is Closure?

Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

What does this mean?

If we apply the method of Hoisting into functions, where we declare first we can use the variables declared in that function within the function in that function. Sounds confusing but once it snaps in your head, you will remember it.

An Example of Closure:

function OuterFunction() {  

    var outerVariable = 1;  

    function InnerFunction() {  
        alert(outerVariable);  
    }  

    InnerFunction();  
 }

So what Closure does, it makes it possible for InnerFunction() to acces outerVariable and make use of it. following this example you would get an alert saying "1".
InnerFunction being able to use variables declared in OuterFunction is called Closure.

When is closure useful?

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.

Sources

Elliott, E. (2019, December 19). Master the JavaScript Interview: What is a Closure? Retrieved May 23, 2021, from https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36#:%7E:text=In%20other%20words%2C%20a%20closure,created%2C%20at%20function%20creation%20time.&text=The%20inner%20function%20will%20have,the%20outer%20function%20has%20returned.

de Meulder, O. (2020, February 14). I never understood JavaScript closures. Retrieved May 23, 2021, from https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8

TutorialsTeacher. (2020). Closure in JavaScript. Retrieved May 23, 2021, from https://www.tutorialsteacher.com/javascript/closure-in-javascript