Scope
ELI5 — The Vibe Check
Scope is about where your variables are visible. Variables defined inside a function can't be seen outside it (that's function scope). Variables defined with let/const inside {} blocks have block scope. Variables at the top of the file are global and visible everywhere (usually a bad idea).
Real Talk
Scope in JavaScript determines the accessibility of variables. ES6 introduced block-scoped let and const (accessible within the nearest {} block), complementing function scope (var, accessible within the enclosing function) and global scope. JavaScript uses lexical (static) scoping — scope is determined at write time, not runtime.
Show Me The Code
const globalVar = 'I am global'
function outer() {
const outerVar = 'I am outer'
function inner() {
const innerVar = 'I am inner'
console.log(globalVar) // accessible
console.log(outerVar) // accessible (closure)
console.log(innerVar) // accessible
}
// console.log(innerVar) // ReferenceError!
}
When You'll Hear This
Prefer const and let over var for predictable block scoping.,Accidental global variables are a common source of bugs.,Understanding scope is key to understanding closures.
Related Terms
Arrow Function
Arrow functions are a shorter way to write functions in JavaScript. Instead of writing 'function(x) { return x * 2 }' you write '(x) => x * 2'.
Closure
A closure is when a function remembers the variables from the scope it was created in, even after that scope is gone.
Hoisting
Hoisting is JavaScript's weird quirk where variable and function declarations are mentally 'moved' to the top of their scope before code runs.