Sitemap
Bollavaram Harshavardhan Reddy

Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced

JavaScript — Scope of Variables

2 min readAug 21, 2024

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.

  1. Global Scope

“The variable declared outside the function or block can accessed throughout the script”

Press enter or click to view image in full size
Example — Global Scope

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.

Press enter or click to view image in full size
Example — Function Scope

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”

Press enter or click to view image in full size

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 👍

--

--

Bollavaram Harshavardhan Reddy
Bollavaram Harshavardhan Reddy

Written by Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced