Explained Global, Local & Block Scope in JavaScript
Source: Dev.to
Scope
Scope generally means the visibility and accessibility of variables in different parts of your code. Understanding the different types of scopes helps write error‑free and clear code.
Global Scope
A variable declared in the global scope is accessible anywhere in the program, including inside functions and blocks.
let global = "I'm a global variable";
function display() {
console.log(global);
}
display(); // "I'm a global variable"
Local Scope
Variables declared inside a function are only accessible within that function.
function local() {
var local = "I'm a local scope variable";
if (true) {
console.log(local); // Works here also inside the if block
}
}
Block Scope
Variables declared with let or const inside a block ({}) are accessible only within that block.
if (true) {
let block = "I'm a block variable";
console.log(block); // Works here inside the block only
}
// console.log(block); // Uncaught ReferenceError: block is not defined
How to declare variables in JavaScript
Variables can be declared using var, let, or const.
var– function‑scoped; can be redeclared and reassigned.let– block‑scoped; can be reassigned but not redeclared.const– block‑scoped; cannot be redeclared or reassigned.
var
console.log("Nikita Maharana");
var a = 25;
var a = 3; // redeclaration allowed
a = 56; // reassignment allowed
console.log(a); // 56
let
let x = 9;
// let x = 5; // ❌ redeclaration not allowed
x = 78; // reassignment allowed
console.log(x); // 78
const
const y = 11;
// const y = 22; // ❌ redeclaration not allowed
// y = 30; // ❌ reassignment not allowed
console.log(y); // 11
Examples
Example 1 – var is function scoped
function fun() {
if (true) {
var a = 55;
}
console.log(a); // 55 – accessible throughout the function
}
fun();
Example 2 – let and const are block scoped
function fun() {
if (true) {
var a = 55;
let b = 34;
const c = 34;
}
console.log(a, b); // a is 55, b is ReferenceError
console.log(c); // ReferenceError – c is block scoped
}
fun();