JavaScript — Scope of Variables
Scope is the term used to explain the accessibility of declared variables in programming languages.
Scoping is a fundamental concept that explains how variables are accessed and used throughout your code.
Javascript’s scoping rules have evolved, especially with introduction of ES6.
The ES6 version introduced new ways to declare variables using “let” and “const” keywords.
- Global Scope
“The variable declared outside the function or block can accessed throughout the script”
When a variable is declared outside a block or function it can accessed anywhere in the code.
In the given example, “globalVariable” is declared outside the function, and the greet function successfully accesses the globalVariable.
Global variables can declared using any keyword used to declare variables.
Get Bollavaram Harshavardhan Reddy’s stories in your inbox
Join Medium for free to get updates from this writer.
2.Function Scope
Variables declared within a function are confined to that function’s scope. They cannot be accessed outside the function in which they are defined.
In the given example while greet function can access globalVariable “userName” cannot be accessed outside the function. The life time of the variable declared inside function is only valid in that particular function.
3.Block Scope
“Variables declared inside a block { } are accessible only within that block”
If a variable is declared in a block introduced in a function the variable is accessible only in that particular block.
In the above example profession is not accessible outside the “if block”.
“While global variables are helpful in some cases it is advised to reduce the usage of global variables.”
Lexical Scoping will be explained in another article on functions.
Thank you for visiting , If you find the article helpful give me a 👍




