Scope and Closures in JavaScript
Scope determines the visibility of variables. Closures allow functions to βrememberβ variables from their outer scope.
π JavaScript Scope
- Global Scope β Variables declared outside any function
- Function Scope β Variables declared inside a function using
var
- Block Scope β Introduced by
let
andconst
inside{ }
let globalVar = "Global";
function testScope() {
let functionVar = "Function";
if (true) {
let blockVar = "Block";
console.log(blockVar); // β
Accessible here
}
// console.log(blockVar); β Not accessible here
}
testScope();
// console.log(functionVar); β Not accessible here
π Closures Explained
A closure is when an inner function accesses variables from an outer function even after the outer function has finished executing.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
π‘ Why Are Closures Useful?
- Encapsulation β Keep variables private
- Data persistence β Remember state across calls
- Functional programming β Create factory functions
π§ Tip: Closures power many JS patterns including callbacks, modules, and event handlers.