This article is going to be about scopes concepts in JavaScript. I'll try my best to explain it in beginner-friendly language. I will talk in this series about some of the most common interview questions that are asked in JavaScript topics. and that is as follows ๐โ
- Scope
- Hoisting
- Call Stack
- Single Thread
in this series of javascript part 1, I will cover only the Scope
Scope in javascript ๐ค:
The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
Type of Scope in javascript ๐ฎ:
there are two types of scope in javascript
- Global scope
- Local scope
- Block scope
- Function scope
Global Scope
A variable declared outside a function becomes GLOBAL Scope. The global scope is the outermost scope in JavaScript. A global variable has Global Scope.
Example :
let x = 2; // Global scope
The variable message is defined in the global scope. let
can be accessed anywhere from the function.
Local scope :
Variables declared inside a function become local to the function. Local functions have Two types of scope and they are
- block scope
- functional scope Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function.
For Example :
var number = 5;
function sum() {
const arr = [1, 2, 3];
let sum = 0;
}
console.log(arr); //code here can NOT use arr
we can not use arr outside of the function because the function variable is declared inside a local function.
Function scope :
JavaScript has a function scope and each function creates a new scope. Variables defined inside a function are not accessible from outside the function.
For Example :
function myFunction() {
let firstName = "Priyanka"; // Function Scope
let lastName = "Chaudhari"; //Function scope
}
Block scope :
Variables declared inside a { } block cannot be accessed from outside the block.
For Example :
{
let x = 2;
}
x cannot be used here
every block scope has its variable that variable can not be accessed by the outside of block { }
conclusion :
Scope refers to the part of a program where we can access a variable. JavaScript allows us to scopes, and variables declared in outer scopes are accessible from all inner ones. Variables can be global, Local, or Functional Scope.
Read another topic in other parts of this series.
If this article gives you some value to understand the concept of Scope then please comment ๐ฉ, likeโค, share with your friends ๐ and follow ๐ค me .