Junior
What is the difference between a closure and a scope?
sobes.tech AI
Answer from AI
Closure is a function that remembers the environment (lexical scope) in which it was created, even if it is executed outside that scope. This allows it to access variables from its parent scope.
Scope is the area of a program where a particular variable or function is visible and accessible. In JavaScript, there are global, functional, and block scopes.
Main difference:
- Scope determines where a variable or function is accessible during compilation (or parsing).
- Closure allows a function to retain access to variables from its creation scope after that scope has finished executing.
Example of scope:
// Global scope
let globalVar = "I am global";
function myFunction() {
// Function scope
let functionVar = "I am functional";
console.log(globalVar); // Accessible
}
// console.log(functionVar); // Error ReferenceError: functionVar is not defined
Example of closure:
function createCounter() {
let count = 0; // Variable in createCounter scope
return function() { // This is a closure
count++; // Has access to count from parent scope
console.log(count);
};
}
const counter = createCounter();
counter(); // Outputs 1 (count is preserved)
counter(); // Outputs 2 (count is preserved)
// console.log(count); // Error ReferenceError: count is not defined
In this example, the inner function (closure) retains access to the variable count, even after createCounter has finished executing. This is possible thanks to closure.
Comparison:
| Characteristic | Scope | Closure |
|---|---|---|
| What it defines | Where variables and functions are accessible | How a function preserves access to variables from its parent scope |
| When active | During compilation (lexical environment) | During execution of a function created in another scope |
| Relation | Closure depends on the scope in which it was created | Scope is a fundamental concept for defining accessibility |