Loading Depth Study
Preparing your workspace
Scope determines where a variable can be accessed, while a closure allows a function to retain access to variables from its lexical environment.
JavaScript has lexical scope, meaning variable access is determined by where code is written. Variables declared with let and const are block scoped. Functions create their own local scope. A closure occurs when an inner function remembers and can access variables from an outer function even after the outer function has finished executing. Closures are common in callbacks, event handlers, factories, and private state patterns.
A function can create a private counter that only changes through returned functions, preventing direct access to the internal value.
function createCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter());
console.log(counter());The console prints 1 and then 2 because the returned function remembers the count variable.