Scope in JavaScript

Scope in JavaScript

This article is focused on a simple explanation of Scope in JavaScript, different types of scopes, and some examples.

Scope

The Scope is a range of any variable where you can access it. Or you can say Scope is a type of container with a specific range of functions and variables. While in JavaScript the default scope is window scope.

Types of Scopes

  • Global Scope
  • Local Scope/Function Scope
  • Block Scope

Global Scope:

The scope of any variable that can be accessed by any function or any other variable from anywhere within the window object. Modifications in the global scope are permanent. If you modified a global variable within a function or without a function then the change will be permanent.

Let us take an example:

  let globalVar = 'Hey this is Aman';  // This is a global variable.

  console.log(globalVar);

Local Scope/Function Scope:

The scope of a variable inside of a function can be accessed only within the function and modifications will limit to that function. Or if we are using a nested function and declare the variable in an outer function and modify it in the inside function then the modifications will be limited to the outer function outside that it will give its original value.

Let us take an example:

let globalVar = 'This is Aman Bisht';   // This is a global variable

function func1(){
      let localVar = 'This is Local Scope';  // This is a local variable
      console.log(localVar);
      console.log(globalVar); 
}
func1();  // calling function
console.log(globalVar); // no error
console.log(localVar);  //  give an error

What if we have a nested function?

function func2(){
      let outer;
          function func3(){
             outer = 'This is local in nested function';
             console.log(outer);  // no error
          }
      func3();
      console.log(outer); // no error
}
func2();
console.log(outer); // reference error

Block Scope:

Block scope tells us that variables that are declared inside a block { }, can be accessed within that block only, not outside of that block.

Let us take an example:

<script>

    {
        let a = 100;
    }
    console.log(a); 
    // reference error 
    // because we can not access any variable outside a block 
    //which is declared inside a block
</script>
Thank you so much for checking this out.

If you have any suggestions write them down in the comment section

If you enjoyed this article don't forget to like, follow, and share.