Scope decides where in the code a variable or function can be accessed. JavaScript has three main levels.
A variable in the global scope, declared outside any function or block, is accessible everywhere. A var or a parameter has function scope, accessible anywhere in its function. A let or const has block scope, accessible only inside the nearest braces. So a var inside an if block still belongs to the whole function, while a let there cannot be read once the block ends.
Scopes nest, so JavaScript resolves a name by checking the current scope first and then each outer scope. That lookup is the scope chain. Keep globals few, because every script on the page shares them and their names can clash.
var globalVar = "global";
function example() {
var functionScoped = "function";
if (true) {
let blockScoped = "block";
const alsoBlock = "block";
}
}
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓