Scope and Scope-Chain in JavaScript.

Scope and Scope-Chain in JavaScript.

What is Scope?

Like any other programming language, JavaScript also uses the concept of scope for variables . The accessibility of an variable in JavaScript is referred to as scope. Which sections of the program can access a given variable and where the variable can be seen. There are mainly three types of scopes-

1. Global Scope

The global scope includes any variable that is not contained within any function or block (a set of curly braces). These variables can be accessed from anywhere in the program. In the below example, the variable greet is a global variable, and it can be accessed anywhere in the program.

Example-

        var greet="say hello";
        function f1(){
            console.log(greet);     // output= say hello      
         }
         f1();
         console.log(greet);      // output= say hello

2. Function/Local Scope

The variable declared inside the function will have local or function scope only, it can only be accessed inside the function ,if we try to access this variable outside the function then it will give a error message. In the below example, if we try to access the variable greet outside the function then it will return Uncaught ReferenceError: greet is not defined.

Example-

      function f1(){
      let greet="say hello";
      console.log(greet);        //  output= say hello  
      }
      f1();
      console.log(greet);   //   Uncaught ReferenceError: greet is not defined.

3. Block Scope

Unlike var variables, let and const variables can be scoped to the nearest pair of curly brackets in ES6. They can't be reached from outside that pair of curly braces, which means they can't be accessed from the outside.

Example-

    {
      let hello = 'Hello!';
      var language = 'Hindi';
      console.log(hello); // 'Hello!' gets logged
     }
    console.log(language); // 'Hindi!' gets logged
    console.log(hello); // Uncaught ReferenceError: hello is not defined

Scope Chain

When we use a variable in JavaScript, first the JavaScript engine looks for the current scope of the variable value. If it can't find the variable in the inner scope, it will look into the outer scope until it finds the variable or reaches the global scope.

If it still can't identify the variable, it will either return an error or implicitly declare the variable in the global scope (if not in strict mode).

Example-

      let a = 'a';
      function f1() {
       let b = 'b';
       console.log(b); // 'b' gets logged
       console.log(a); // 'a' gets logged
       }
     f1();