JavaScript closures: outer scope access and information hiding
What is a closure? It is an inner function's access to the context of its outer function.
Then is every regular function that refers to a global variable also a closure?
- Of course not. A closure has a closed-off feel, like an inner function bundled up inside an outer function.
Here is a closure example.
function outer() {
const x = 0;
function inner() {
console.log(`inside inner: ${x}`); // can access the outer function's variable because of how closures work
}
return inner;
}
const func = outer(); // gets not only the inner function but also a reference to the outer function's lexical environment
func();I assigned outer() to a variable named func and ran func(). You can see that the console.log() statement in inner(), the inner function inside outer(), runs.
Here is a more precise example.
function count() {
let count = 0;
function up() {
count++;
console.log(count);
}
return up;
}
const countFunc = count(); // data in the outer function's lexical environment can be changed through the inner function
countFunc();
countFunc();I assigned the count() function to the countFunc variable. The count variable declared in the outer function's lexical environment starts at 0. But what happens when you run countFunc() from outside?
That's right. Through the inner function up(), you can change the value of the count variable declared in the outer function.
This is the biggest feature of closures.
Also, the outside code changes the value through the inner function instead of reaching it directly, so we could see another big feature: it can hide information.
One-line summary: a closure is an inner function being able to access its outer function's context, and its biggest features are encapsulation and information hiding!
- #examples
- #information hiding
- #encapsulation
- #closures