Scope in JavaScript

What is Scope in JavaScript? How to handle Scope in javaScript?      July 29, 2021

Shubham Verma

Shubham Verma

Scope in JavaScript

What is Scope in JavaScript? How to handle Scope in javaScript?

The scope is related to variables in the JavaScript, scope determines the accessibility or visibility of variables in the Javascript.
Before ES6, JavaScript had only two kind of scopes:

1. Global Scope
2. Function Scope

In the ES6, the Block level scope introduced with let and const keywords.

Now JavaScript has 3 types of scope:
1. Global Scope
2. Function Scope
3. Block level

Global Scope:

In the JavaScript, those variables which are declared Globally or outside the function have the global dcope in nature. Those global variables can be accessed from anywhere in that codes/program.

In JavaScript, objects and functions are also variables.

If you write codes where you haven't declared a variable but you assigned some value to it, this also will be a global variable and scope will be global.

In "Strict Mode", undeclared variables are not automatically global.

Function Scope:

In the javaScript, all function creates their own scope called function scope. Variables defined within the function are not accessible outside the function.

Block Scope:

When we write our code inside the {...}, the variables inside the block have Block level scope. Variables declared inside a { } block cannot be accessed from outside the block.

The blocl scope is not ruled on var keyword. It means aariables declared with the var keyword can NOT have block scope and variables declared inside a { } block is accessible from outside the block.

Note: Function arguments (parameters) work as local variables inside functions.

Local Scope:

We have a local scope also, those variables who is declared inside the functions, has the local scope in nature.

Local variables have their identity inside that function only where they have declared, so it provides the advantages, variables with the same name can be used in different functions. In the JavaScript, Local variables are created when a function starts, and deleted when the function is completed.

Thank you

for taking the time to read this article. If you’re interested in Node.js or JavaScript this link will help you a lot.

If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also. You can follow us on our social media page for more updates and latest article updates.
To read more about the technologies, Please subscribe us, You'll get the monthly newsletter having all the published article of the last month.