Home >Web Front-end >JS Tutorial >Scopes and scope chains in JavaScript explained

Scopes and scope chains in JavaScript explained

PHPz
PHPzforward
2023-09-07 09:25:02993browse

解释 JavaScript 中的作用域和作用域链

In JavaScript, Scope defines how and in which part of the code we access variables and functions. Simply put, scope can help us improve the safety and readability of our code. Therefore, we can only access variables and functions within their scope and not outside them.

We will discuss various types of scopes in this tutorial.

Global Scope in JavaScript

Globally defined variables and functions are meant outside all blocks and functions that have global scope. We can access all variables and functions with global scope anywhere in the code.

grammar

Users can define variables with global scope according to the following syntax.

var global = 30;
function func() {
   var b = global; // global variable has a global scope so we can access it inside the function.
}

Here, the global variable global is declared outside any function, so it has global scope. It is then accessed inside function func by declaring local variable b and assigning the value of global variable global to it.

Example

In this example, we define a global variable with global scope. We access it inside a function called func() and return its value from the function.

In the output, we can observe that the func() function returns 20, which is the value of the global variable.

<html>
   <body>
      <h2> Defining a variable with <i> global </i> scope </h2>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         var global = 20;
         function func() {
            return global;
         }
         output.innerHTML += "The value of variable named global: " + func();
      </script>
   </body>
</html>

Local/function scope

Local scope is also called function scope. Variables defined inside a function have function scope/local scope. We cannot access variables outside the function.

grammar

You can follow the syntax below to understand the local scope of variables and functions -

function func() {
   var local_var = "Hi!";
}
console.log(local_var); // this will raise an error

Here local_var There is a function scope inside the func() function, so we cannot access it outside it.

Example

In this example, we create the func() function. Inside the func() function, we have defined the local_var variable with local scope, which means we can only access it inside the func() function. We can see that if we try to access local_var outside the func() function, an error is thrown because local_var is undefined. To see this error, you need to open a console.

<html>
   <body>
      <h2>Defining a variable with <i> function </i> scope</h2>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         function func() {
            let local_var = 20;
            output.innerHTML += "The value of local_var inside fucntion: " + local_var + "<br/>";
         }
         func();
         // the local_var can't be accessed here
         output.innerHTML += "The value of local_var outside fucntion: " +local_var+ "<br/>";
      </script>
   </body>
<html>

Block Range

In JavaScript, we can use two curly braces ({ ….. }) to define a block. Block scope means that any variable we define within a particular block can only be accessed within the block and not outside the block. Variables declared using the let and const keywords have block scope.

grammar

Users can follow the following syntax to understand the block scope of variables.

{
   let block_var = 6707;
   // block_var accessible here
}

// we can't access the block_var variable here.

Here, we cannot access the block_var outside the curly braces because we have defined it inside the specific block.

Note - Variables declared using the var keyword do not have block scope.

Example

In this example, we use curly braces to define a block and define a variable num. We try to access this variable inside and outside the block. You can observe that we cannot access num outside the curly braces because we have defined it inside the block.

<html>
   <body>
      <h2>Defining the variable with <i> block </i> scope </h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         {
            const num = 200;
            output.innerHTML += "Value of num inside the block: " + num + "<br>";
         }
         // num is accessible here - outside the block
         output.innerHTML += "value of num outside the block: " + num + "<br>";
      </script>
   </body>
</html>

lexical scope

Lexical scope is the same as static scope. In JavaScript, when we execute a nested function and try to access any variable inside the nested function, it first finds the variable in the local context. If it cannot find the variable in the local context of the nested function, it tries to find it in the parent context of the function's execution, and so on. Finally, if the variable is not found in the global context, it is considered undefined.

grammar

Users can follow the following syntax to understand lexical scope.

var parent_var = 343;
var test = function () {
   console.log(parent_var);
};
test();

In the above syntax, we access parent_var from the scope of function execution. Since the function log() will not find parent_var in the local scope, it will try to find it in the scope where the function is called (i.e. the global scope).

Example

In this example, we define the test() function and nested() function inside. Furthermore, we are accessing global_var and parent_var inside the nested() function. Since JavaScript won't find these two variables in the local context, it will look first in the execution context of the nested() function and then in the execution context of the test() function.

<html>
   <body>
      <h2>Defining the variables with <i> lexical </i> scope</h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         var global_var = 576505;
         var test = function () {
            var parent_var = 343;
            var nested = function () {
               output.innerHTML += "The value of parent_var: " + parent_var + "<br/>";
               output.innerHTML += "The value of global_var: " + global_var + "<br/>";
            };
            nested();
         };
         test();
      </script>
   </body>
</html>

Scope chain

As scope chain the term implies, it is a scope chain. For example, suppose we define a nested function inside a function. In this case it can have its local scope and variables declared inside the nested function cannot be accessed in the outer function.

So, we are creating a scope chain; that's why we call it a scope chain.

grammar

Users can follow the following syntax to understand the scope chain.

function outer() {
   function inner() {
      // inner’s local scope.
      
      // we can access variables defined inside the outer() function as inner is inside the local scope of outer
   }
   
   // variables defined in the inner() function, can’t be accessible here.
}

Example

In this example, the inner() function is within the scope of the outer() function, which means that we cannot call the inner() function outside the outer() function. The inner() function creates the scope chain inside the outer() function.

<html>
   <body>
      <h2>Scope Chain in JavaScript </i></h2>
      <div id="output"></div>
      <script>
         let output = document.getElementById("output");
         function outer() {
            var emp_name = "Shubham!";
            function inner() {
               var age = 22;
               output.innerHTML += ("The value of the emp_name is " + emp_name) +"<br/>";
               output.innerHTML += "The value of the age is " + age;
            }
            inner();
            
            // age can't be accessible here as it is the local scope of inner
         }
         outer();
      </script>
   </body>
</html>

在本教程中,我们讨论了 JavaScript 中的作用域和作用域链。我们讨论了全局、局部/函数、块和词法作用域。在上一节中,我们了解了作用域链在 Javascript 中的工作原理。

The above is the detailed content of Scopes and scope chains in JavaScript explained. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete