DEV Community

Cover image for What is a SCOPE in javascript ?
Vishal Heble
Vishal Heble

Posted on

What is a SCOPE in javascript ?

Scope is the execution context area and the ability to access a variable based on how you declare them. One important difference between JavaScript and other languages mostly C-based languages is Variables are created at the spot(execution context area) where they are declared in latter case. But in JS, the variables are created in a spot depending on how you declare them.

There are 2 types of scopes :

1) Global Scope
The area outside function is considered a global scope (window). So a variable can be accessed in other scopes (functions/blocks) as well.

Alt Text

2) Local Scope
It has 3 different types :

a) Function Scope
When you declare a variable inside a function, it is accessible within function only.

Alt Text

Note: This is same for let and const as well.

b) Block Scope
In ES6, let and const allow to declare variables in a block scope where in the variable is accessible only within the curly braces { } or a block like for and while loops, if and switch conditions etc.

Alt Text

c) Lexical Scope
The child scope have access to the variables defined in its parent scope.

Alt Text

Top comments (0)