Fetching latest headlines…

Dev

Variable Scope in JavaScript

Dev.toUnited States · NORTH AMERICA

What Is Variable Scope? Variable scope means where we can access a variable in our code. A variable declared in one place may not be accessible from another place. Understanding scope helps us avoid...

0 views0 likes0 comments

What Is Variable Scope?

Variable scope means where we can access a variable in our code.

A variable declared in one place may not be accessible from another place. Understanding scope helps us avoid errors and write better code.

Let's look at the three basic types of scope.

1. Global Scope

A variable declared outside a function or block can be accessed from different parts of the program, depending on the execution context.

let name = "John";

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

greet();

Output:

John

Here, name is declared outside the function. So, the function can access it.

2. Function Scope

A variable declared inside a function can be accessed only within that function and its nested scopes.

function greet() {
    let message = "Hello World!";
    console.log(message);
}

greet();

Output:

Hello World!

If we try to access message outside the function, JavaScript gives a ReferenceError.

function greet() {
    let message = "Hello World!";
}

console.log(message);

Here, message cannot be accessed outside greet().

3. Block Scope

A block is a section of code enclosed in curly braces { }, such as an if statement or a loop.

Variables declared with let and const inside a block can only be accessed within that block.

if (true) {
    let age = 20;
    console.log(age);
}

Output:

20

But if we try to access age outside the block, we get a ReferenceError.

if (true) {
    let age = 20;
}

console.log(age);

This happens because age belongs to the if block.

What About var?

Unlike let and const, var is not block-scoped.

if (true) {
    var city = "Chennai";
}

console.log(city);

Output:

Chennai

This works because var is function-scoped rather than block-scoped.

Why Is Variable Scope Important?

Understanding scope helps us:

  • Know where a variable can be accessed.
  • Avoid ReferenceError errors.
  • Prevent unnecessary access to variables.
  • Organize our code more clearly.

Comments (0)

Sign in to join the discussion

Be the first to comment!