Skip to main content

Closure


A closure is the ability to access a parent level scope from a child scope, even after the parent function has been terminated.

function outer() {
const outerVar = "Hey I am the outer Var";
function inner() {
const innerVar = "hey I am an inner var";
console.log(innerVar);
console.log(outerVar);
}
return inner;
}
const innerFn = outer();
innerFn();

We ran the outer() function on this line of code const innerFn = outer();, which is where it created the variable, and then it returned the inner function.

Is that still going to be available to us or will it be undefined?

If you try that code, you will see that they both work.

What you can do is stick a function into a variable, and then at a later point in time, you can have access to that function. A closure comes into play because you can access the function even though the outer function is done.

We learned in scoping that when a function is done, anytime there are scoped variables that aren't returned from the function, they are not accessible.

Now we get this weird thing where when we run the function outside of it, it's still able to access it. That is what is referred to as a closure.