Scope & closures — where variables live
Where can a variable be seen?
Scope simply means: which parts of your code can see a variable. A variable made inside { } lives only inside those braces.
function test() {
let secret = 42;
console.log(secret); // works
}
test();
console.log(secret); // error! secret is not visible out here
secret is local to the function. Outside, it does not exist. This is a good thing — it stops different parts of your program from clashing.
Inner can see outer
An inner function can see the variables of the function around it:
function greeting(name) {
function say() {
console.log("Hi " + name); // 'name' is visible here
}
say();
}
greeting("Riya");
What is a closure?
A closure is when an inner function remembers the variables from where it was created — even after the outer function has finished.
function counter() {
let count = 0;
return () => {
count = count + 1;
return count;
};
}
let next = counter();
console.log(next()); // 1
console.log(next()); // 2
Even though counter() already finished, the returned function still remembers count. That memory is the closure. It is how functions keep private, remembered data.
Scope = where a variable can be seen. Closure = an inner function remembering its outer variables. Do not worry if it feels deep — it clicks with practice.