Skip to main content

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.

javascript
let name = 'Tim'; // global variable function greet() { console.log('Hello, ' + name); // accessible here } greet(); // Hello, Tim console.log(name); // also accessible here

2. Function Scope

Variables declared with var, let, or const inside a function are accessible only inside that function.

javascript
function example() { let message = 'Inside function'; console.log(message); // works } example(); console.log(message); // Error: message is not defined

3. Block Scope

Variables declared with let or const inside a block { } are accessible only inside that block.

javascript
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); // Error

4. 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.

javascript
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, inner remembered the environment in which it was created - this is exactly what a closure is.


Summary

Scope typeWhere it is createdAccessibility
GlobalOutside functions and blocksEverywhere
FunctionInside a functionOnly inside that function
BlockInside { } (if, for, etc.)Only within the block
LexicalAt the time the code is writtenAccess to variables from outer scopes

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.