January 2020
Intermediate to advanced
470 pages
11h 13m
English
Closures are a way to implement data hiding (with private variables), which leads to modules and other nice features. The key concept of closures is that when you define a function, it can refer to not only its own local variables but also to everything outside of the context of the function. We can write a counting function that will keep its own count by means of a closure:
function newCounter() { let count = 0; return function() { count++; return count; };}const nc = newCounter();console.log(nc()); // 1console.log(nc()); // 2console.log(nc()); // 3
Even after newCounter() exits, the inner function still has access to count, but that variable is not accessible to any other parts of your code.
Read now
Unlock full access