![]() |
VOOZH | about |
Scope in JavaScript defines where a variable can be accessed or used within a program. It controls the visibility and lifetime of variables across different parts of the code.
There are several types of scopes of a variable. Let us understand these one by one.
The image below shows Global and Local Scope in JavaScript to help understand their accessibility.
A global variable refers to a variable that is declared outside any function or block, so it can be used anywhere in the program, both inside functions and in the main code.
The variable x is declared in the global scope and can be accessed inside functions. However, global scope behavior may vary depending on the execution environment (e.g., browser vs module).
A local variable is a variable declared inside a function, making it accessible only within that function. It cannot be used outside the function.
Here, the code defines a function fun2 with a local variable x, which is accessible only inside the function, and prints its value when the function is called.
var, which is function-scoped (accessible within the function) and globally Scoped (Accessible everywhere) and prone to issues like hoisting and global pollution.The image below shows Block and Lexical Scope in JavaScript to help understand their accessibility.
Block scope in JavaScript means variables declared with let or const inside { } are accessible only within that block, and accessing them before declaration (TDZ) causes a ReferenceError.
Variables declared with var do not have block scope. A var variable declared inside a function is accessible throughout that entire function, regardless of any blocks (like if statements or for loops) within the function. If var is declared used outside of any function, it creates a global variable.
We have successfully accessed the variable with the var keyword because var does not have a block scope.
The variable is declared inside the function and can only be accessed inside that block or nested block is called lexical scope.
This code demonstrates lexical scope, where func2 accesses the variable x from func1 and prints “10 20”.
Module scope refers to variables and functions that are accessible only within a specific JavaScript module. It helps keep code organized and prevents variables from affecting the global scope.