Scope determines where a variable is visible and accessible in your code.
- Global scope — accessible everywhere in the file/program
- Function scope — var is confined to the nearest enclosing function
- Block scope — let/const are confined to the nearest { } block
- Lexical scoping — inner functions can access outer variables (the basis of closures)
let outer = 'I am outer';
function outerFn() {
let inner = 'I am inner';
if (true) {
let blockScoped = 'only visible here';
console.log(outer, inner, blockScoped); // all work
}
// console.log(blockScoped); // ReferenceError
}