Scopes And Scope Chain in JavaScript

Md Pervez Hossain - May 27 - - Dev Community

What is Scope In JavaScript ?

Scope in JavaScript defines the space in which variables and functions are accessible. It determines the visibility and lifecycle of these variables and functions, influencing where and how they can be used within your code.

In JavaScript, there are three main types of scope:

  • Global Scope
  • Function/Local Scope
  • Block Scope

These scopes serve the accessibility of variables within different sections of your code. Understanding and correctly implementing scope Makes your Code organized and preventing variable conflicts.

Global Scope in JavaScript :
Global scope is the widest scope available in JavaScript. Variables declared in this scope are accessible from anywhere in the code, Just make the Variables universally accessible and available

Key Points of Global Scope : 👍

  • Variables declared in the global scope can be accessed from any where of your code, including inside functions, conditionals, loops, and other blocks.
  • Typically, global variables are declared outside any functions or code blocks.

Image description

Here globalvar variable is accessible any of your code . Even The Nested Function and block Scope

  • Using too many global variables can lead to conflicts and unmanageable
  • Global variables can be accidentally overwritten, Making bugs and unpredictable behavior.

Image description

Here "counter" variable is a global Variable and Assign a number .

The increment function correctly increments the **counter variable 0 to 1.

The "process function" mistakenly overwrites the counter with a string. When you call process, it changes the type of counter to a string, which causes "unexpected behavior" when you later try to increment it with increment because you cannot perform arithmetic operations on a string in the same way .

This is how global variables can be "accidentally overwritten" and lead to bugs or unpredictable behavior in your code.

  • Use functions and block scopes (let and const) to encapsulate variables and limit their accessibility.
  • In browsers, global variables become properties of the window object.

Local Scope in JavaScript :

Local scope in JavaScript refers to the visibility and accessibility of variables within a specific block of code, such as a function, loop, or conditional statement. Variables declared in this scope are only accessible within that particular block.

It allows you to write organized, modular, and less error code, contributing to a more robust and maintainable codebase.

Key points Of Local Scope : 👍

  • Variables are only accessible within the block of code, function, or conditional statement where they are declared.

Image description

"localVariable" is declared inside the "myFunction" function.

"localVariable" is accessible within the "myFunction" function, as shown by the console.log statement inside the function.

Outside of "myFunction", trying to access "localVariable" results in an error because "localVariable" is not defined in the global scope.

local scope can also be demonstrated using block scope like if statements or loops:

Image description

"blockScopedVariable" is declared inside an if block.
"blockScopedVariable" is accessible within the if block, as shown by the console.log statement inside the block.

Outside of the if block but still within the "checkScope" function, trying to access "blockScopedVariable" results in an error because "blockScopedVariable" is not defined outside of its block.

  • Provides protection from external Changes and accidentally modified outside their scope.
  • Think of local scope as Your private room, where anyone cannot be accessed directly from outside the room.
  • Local scope making Your Code more manageable and easier to maintain.

Variable Shadowing in JavaScript :

Variable shadowing occurs when a variable declared within a local scope has the same name as a variable in an outer scope, effectively "hiding" the outer variable. The local variable takes precedence within its scope.

  • When a variable is shadowed, the inner scope's variable is accessed instead of the outer scope's variable.

Image description

A global variable count is declared and initialized with the value 10.
Inside the outerFunction, a local variable count is declared with the value 20, shadowing the global variable count.

Inside the if block, another local variable count is declared with the value 30, shadowing the count variable in the outerFunction scope.

The console.log statements show the values of count in different scopes, demonstrating how the closest variable declaration is used and shadows any outer variables with the same name.

When console.log of count in the global scope , output of count is 10, because Here no Variable shadows the global variable count

Block Scope in JavaScript :

Block scope in JavaScript refers to the scope that restricts variables to the block where they are declared. A block is defined by a pair of curly braces {} and is commonly used in functions, loops, and conditional statements.

Key Points of Block Scope : 👍

  • Variables declared using let and const are block-scoped, meaning they are only accessible within the block they are defined in.
  • Block scope helps prevent variables from being accessed or modified outside their context, Prevent Variables From side effects and bugs.

Image description

loopScopedVariable and the loop counter **i **are declared inside the for loop using let.

Both variables are accessible within the for loop block, as shown by the console.log statements inside the loop.

Outsidethe for loop but within the testLoopScope function, trying to access loopScopedVariable and i results in a ReferenceError because they are not defined outside their block scope.

  • 3. block scope , keeps your code clean and maintainable by limiting variable visibility to where they are needed.
  • 4. Variables declared in block scope are only accessible within the block in which they are defined.

Difference Between Local Scope and Block scope :

  • Local scope is defined by functions.
  • Block scope is defined by blocks (e.g., {} in loops, conditionals).
  • Local scope can use var, let, or const (though var is function-scoped).
  • Block scope uses let and const.
  • Local scope variables are accessible throughout the entire function.
  • Block scope variables are only accessible within the block they are declared in.

What is scope chain ?

When JavaScript Engine Try to access a variable, JavaScript starts from the inner most scope and moves outer Scope until it finds the variable or reaches the global scope. This Processing of Searching variable is called the scope chain In JavaScript .

Image description

  1. globalVar is declared in the global scope.
  2. outerVar is declared in the outerFunction scope.
  3. innerVar is declared in the innerFunction scope.

👉 When innerFunction is executed:

It first looks for innerVar within its own scope and finds it.

For "outerVar", it doesn't find it within the "innerFunction" scope, so it moves to the next outer scope, which is the "outerFunction" scope, and finds it there.

For "globalVar", it doesn't find it within the "innerFunction or outerFunction" scopes, so it moves to the global scope and finds it there.

👉 When outerFunction is executed:

It can access "globalVar" from the global scope and "outerVar" from its own scope.

It cannot access "innerVar" because innerVar is only available within the "innerFunction" scope.

👉 When accessing variables from the global scope:

Only globalVar is accessible.

outerVar and innerVar are not accessible because they are scoped within their respective functions.

This example Shows how the scope chain works in JavaScript, where the engine searches for variables from the innermost scope to outer Scope until it finds the variable or reaches the global scope.

. . . . . . . . . . . . . . .
Terabox Video Player