Global and local scope in Javascript
Understand about global and local scope with the help of easy examples and easy explanation.
Table of contents
JavaScript variables can be declared using var
, let
, or const
. The scope of these variables depends on how they are declared and where they are used. Let's explore the concepts of block scope and global scope with an example.
let a = 200;
if (true) {
let a = 10;
const b = 20;
var c = 30;
console.log("Inner: ", a); // Outputs: Inner: 10
}
console.log(a); // Outputs: 200
console.log(b); // Error: b is not defined
console.log(c); // Outputs: 30
Explanation
Global Scope: Variables declared outside any block (e.g.,
let a = 200;
) are in the global scope. They can be accessed from anywhere in the code.Block Scope: Variables declared with
let
orconst
inside a block (e.g., inside anif
statement) are only accessible within that block. In this example:let a = 10;
andconst b = 20;
are in block scope. They can't be accessed outside theif
block.
Function Scope: Variables declared with
var
are function-scoped or globally-scoped if declared outside any function. In this example:var c = 30;
is accessible both inside and outside theif
block becausevar
does not respect block scope, it only respects function scope.
Key Takeaways
Block Scope with
let
andconst
: These variables are limited to the block where they are defined.Global Scope with
var
: Variables declared withvar
can be accessed outside the block they are defined in if they are not inside a function.Scoping Rules: Understanding these rules helps avoid errors and unintended behavior in your code.
Practical Usage
Block Scope Example
if (true) {
let blockScoped = "I am block scoped";
console.log(blockScoped); // Outputs: I am block scoped
}
console.log(blockScoped); // Error: blockScoped is not defined
Global Scope Example
var globalScoped = "I am global scoped";
if (true) {
console.log(globalScoped); // Outputs: I am global scoped
}
console.log(globalScoped); // Outputs: I am global scoped
Understanding the difference between block scope and global scope is crucial for writing clean, maintainable, and bug-free JavaScript code.