JavaScript Scope
Scope determines where a variable is accessible in your code. JavaScript has global scope, function scope, and (with let/const) block scope.
Variables declared inside a function or block are not visible outside it, which helps prevent naming collisions and keeps code modular.
Block scope vs function scope
`let` and `const` are block-scoped โ confined to the nearest `{}`. `var` is function-scoped, ignoring block boundaries like if-statements.
Global scope
Variables declared outside any function or block are globally accessible, but polluting global scope is generally considered bad practice.
if (true) {
let x = 10;
console.log(x);
}
// console.log(x); would throw an error here10x is block-scoped and inaccessible outside the if-block.
function outer() {
let msg = "hello";
function inner() {
console.log(msg);
}
inner();
}
outer();helloInner functions can access variables from their enclosing scope.
Key points
- let/const are block-scoped; var is function-scoped.
- Inner scopes can access outer (enclosing) variables.
- Outer scopes cannot access inner scope variables.
- Minimizing global variables reduces naming conflicts and bugs.
