Syntax
{ /* block scope */ }
function() { /* function scope */ }Examples
Global vs Function Scope
Variables declared at the top level vs inside a function.
const globalVar = "I am global";
function myFunction() {
const localVar = "I am local";
console.log(globalVar); // accessible - inner scope sees outer scope
console.log(localVar);
}
myFunction();
// console.log(localVar); // ReferenceError - not accessible outside the functionBlock Scope with let/const
let and const respect block boundaries, unlike var.
if (true) {
let blockScoped = "only visible in this block";
var functionScoped = "visible outside the block";
}
// console.log(blockScoped); // ReferenceError
console.log(functionScoped); // works - var ignores block boundariesScope Chain
Nested functions can access variables from every enclosing scope.
const outer = "outer value";
function level1() {
const middle = "middle value";
function level2() {
const inner = "inner value";
console.log(outer, middle, inner); // all accessible via the scope chain
}
level2();
}
level1();Best practices
- Keep variables scoped as narrowly as possible - declare them inside the block or function where they are actually used
- Avoid polluting the global scope - wrap code in functions or modules rather than declaring everything globally
- Use let/const for predictable block scoping instead of var's looser function scoping
- Understand the scope chain when debugging "variable is not defined" errors - the variable may simply be out of reach from where you are trying to access it
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification