DEV Community

Sai Chandu
Sai Chandu

Posted on

Scope of a Variable in JavaScript

Welcome back to another interesting and an exciting concept in JavaScript is Scope of a variable.

The Scope of Variable is defined as the context of a program in which it can be accessed. They are three ways of defining the scope of a variable.

Image description

1.Global Scope
2.Local Scope
3.Functional Scope
4.Block Scope
Now, we can see how these types of scopes were used differently in js.

1.Global Scope: Variables declared Globally(means outside function) have Global scope they can be accessed from anywehre in a program. Variables declared with var keyword can have global scope.

2.Local Scope: Variables declared inside a function becomes local to the function. We can access the values of those variables within that function only.

3.Function Scope: JavaScript has a function scope and each function can have their own scope. Variables declared with in the function are not allowed to access outside the function.

4.Block Scope: Earlier JavaScript has only Global Scope and Function Scope, but in ES6 2015 they introduce let and const with them we can have block scope. The variables declared with let and const are been accessed for that particular block.

This is all about the Scope of a variable in JavaScript.

Hope you guys learn about the scope. See you in next lecture🤠

Top comments (0)