Scope of Variables in JavaScript

작성자

카테고리:

← 피드로
DEV Community · Pranay Rebeyro · 2026-07-12 개발(SW)

Pranay Rebeyro

Scope
A variable is not always available everywhere in your program. Some variables can be used anywhere, while others can only be used inside a function or a block.This is called Scope.

Types of Scope in JavaScript

Global Scope – A variable declared outside any function or block is called a Global Variable.It can be accessed from anywhere in the program.

Eg:
let name = "Pranay";

function greet() {
    console.log(name);
}

console.log(name);

greet(); // Output:
Pranay
Pranay

Enter fullscreen mode Exit fullscreen mode

Function Scope – Variables declared inside a function can only be used inside that function.

Eg:
function student() {
    let age = 20;

    console.log(age);
}

student(); // Output: 20

// If you try to access age outside the function
function student() {
    let age = 20;
}

console.log(age); // Output: ReferenceError: age is not defined

// This happens because age exists only inside the function.

Enter fullscreen mode Exit fullscreen mode

Block Scope – A block is anything inside curly braces { }.Variables declared using let and const inside a block can only be accessed within that block.

Eg:
if (true) {
    let city = "Chennai";

    console.log(city);
} // Output: Chennai

// Trying to access it outside the block
if (true) {
    let city = "Chennai";
}

console.log(city); // Output: ReferenceError: city is not defined

Enter fullscreen mode Exit fullscreen mode

  1. var – Function-scoped and not block-scoped.
  2. let and const – Block-scoped

Variable Hoisting
Hoisting means JavaScript processes declarations first, before running the program.

Hoisting – var and function
Non-Hoisting – let and const

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다