What is scope (variable visibility)?
Scope is a mechanism in JavaScript that determines where in the code variables and functions are accessible (that is, in which parts of the program they can be referenced).
Main types of scope
1. Global Scope
Variables declared outside functions or blocks are accessible everywhere in the code.
let name = 'Tim'; // global variable
function greet() {
console.log('Hello, ' + name); // accessible here
}
greet(); // Hello, Tim
console.log(name); // also accessible here2. Function Scope
Variables declared with var, let, or const inside a function are accessible only inside that function.
function example() {
let message = 'Inside function';
console.log(message); // works
}
example();
console.log(message); // Error: message is not defined3. Block Scope
Variables declared with let or const inside a block { } are accessible only inside that block.
if (true) {
const x = 10;
let y = 20;
var z = 30; // var has no block scope
}
console.log(z); // 30 (var is visible outside the block)
console.log(x); // Error
console.log(y); // Error4. Lexical Scope
JavaScript uses lexical (static) scope - this means that access to variables is determined by where functions are located in the code, not by where they are called.
function outer() {
const outerVar = 'I am outside';
function inner() {
console.log(outerVar); // has access to outerVar
}
return inner;
}
const fn = outer();
fn(); // "I am outside"Here,
innerremembered the environment in which it was created - this is exactly what a closure is.
Summary
| Scope type | Where it is created | Accessibility |
|---|---|---|
| Global | Outside functions and blocks | Everywhere |
| Function | Inside a function | Only inside that function |
| Block | Inside { } (if, for, etc.) | Only within the block |
| Lexical | At the time the code is written | Access to variables from outer scopes |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.