DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Mahin Tazuar
Mahin Tazuar

Posted on • Updated on

About Scope Inside , Javascript

Today we are talking about scope. Which tricky things in javascript. Actually, javascript is a tricky language. javascript one of the Tricky things is Scope. If we are want to deeply understand javascript, we need to understand the scope. That is the most common interview question too.
Javascript have 2 scope, which is :

  1. Global scope
  2. block scope.
  3. Local scope/function scope
  4. lexical scope

1.Global scope :
when we define a variable with a value outside any block that variable creates an environment. everywhere we can access this variable as a window object but we do not need to write a window. variable.
code example :

var a = 10;
function f() {
console.log(a) // access global variable
}
console.log(a) // access global variable
Enter fullscreen mode Exit fullscreen mode
  1. block scope : all js blocks create with scond brackets. we understand about global scope. Now are going for the local scope. When we define a variable with value inside a block like for loop, etc and that variable can not access outside from this block. This environment calls block scope in javascript.
function f() {
let a = 10;
console.log(a) // access global variable
}
console.log(a) // can not acess this variable
Enter fullscreen mode Exit fullscreen mode

3.function scope / local scope :
when we are define a variable inside a functioin and we can get access the variable only inside the function. We can not get access the acess outside the function . Thats why its called block scope and functional scope.

  1. lexical scope : when we are using a function, If any variable define inside the function we can got this variable inside all child function. like a chain .That is called lexical scope .

Top comments (0)

🌚 Life is too short to browse without dark mode