Table of Contents
Global Scope in JavaScript
grammar
Example
Local/function scope
Block Range
lexical scope
Scope chain
Home Web Front-end JS Tutorial Scopes and scope chains in JavaScript explained

Scopes and scope chains in JavaScript explained

Sep 07, 2023 am 09:25 AM

解释 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.
}
Copy after login

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>
Copy after login

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
Copy after login

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>
Copy after login

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.
Copy after login

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>
Copy after login

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();
Copy after login

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>
Copy after login

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.
}
Copy after login

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>
Copy after login

在本教程中,我们讨论了 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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles