Table of Contents
Global scope
Module scope
Function Scope
Block scope
Lexical Scope
Scope Chain
Summary
Home Web Front-end JS Tutorial Comprehensive analysis of JavaScript scope (with code)

Comprehensive analysis of JavaScript scope (with code)

Apr 03, 2019 am 10:27 AM
javascript Scope front end

This article brings you a comprehensive analysis of JavaScript scope (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Scope determines the life cycle and visibility of variables. Variables are invisible outside the scope.

The scope of JavaScript includes: module scope, function scope, block scope, lexical scope and global scope.

Global scope

Variables defined outside the scope of any function, block, or module have global scope. Global variables can be accessed anywhere in the program.

Creating global variables becomes more difficult when the module system is enabled, but it can still be done. You can define a variable in HTML that needs to be declared outside the function, so you can create a global variable:

<script>
  let GLOBAL_DATA = { value : 1};
</script>
console.log(GLOBAL_DATA);
Copy after login

Creating global variables is much easier when there is no module system. Variables declared outside functions in any file are global variables.

Global variables run throughout the entire life cycle of the program.

Another way to create global variables is to use the window global object anywhere in the program:

window.GLOBAL_DATA = { value: 1 };
Copy after login

This way the GLOBAL_DATA variable will be everywhere .

console.log(GLOBAL_DATA)
Copy after login

But you also know that this approach is bad.

Module scope

If the module is not enabled, variables declared outside all functions are global variables. In a module, variables declared outside a function are hidden and are not available in other modules unless explicitly exported.

Exports make functions or objects available to other modules. In this example, I exported a function from the module file sequence.js:

// in sequence.js
export { sequence, toList, take };
Copy after login

The current module can use functions or objects of other modules by importing them.

import { sequence, toList, toList } from "./sequence";
Copy after login

To a certain extent, we can think of the module as an automatically executed function that takes the imported data as input and then returns the exported data.

Function Scope

Function scope means that parameters and variables defined in a function are visible anywhere within the function, but not outside the function.

The following is an automatically executed function called IIFE.

(function autoexecute() {
    let x = 1;
})();
console.log(x);
//Uncaught ReferenceError: x is not defined
Copy after login

IIFE means immediate invocation of function expression, which is a function that runs immediately after definition.

Variables declared with var have only function scope. More importantly, variables declared with var are promoted to the top of their scope. This way they can be accessed before they are declared. Take a look at the following code:

function doSomething(){
  console.log(x);
  var x = 1;
}
doSomething(); //undefined
Copy after login

This kind of thing doesn't happen in let. Variables declared with let can only be accessed after they are defined.

function doSomething(){
  console.log(x);
  let x = 1;
}
doSomething();
//Uncaught ReferenceError: x is not defined
Copy after login

Variables declared with var can be redeclared multiple times in the same scope:

function doSomething(){
  var x = 1
  var x = 2;
  console.log(x);
}
doSomething();
Copy after login

Use let or const Declared variables cannot be redeclared in the same scope:

function doSomething(){
  let x = 1
  let x = 2;
}
//Uncaught SyntaxError: Identifier 'x' has already been declared
Copy after login

Maybe we can stop caring about this because var is starting to become obsolete.

Block scope

Block scope is defined with curly braces. It is separated by { and }.

Variables declared with let and const can be constrained by block scope and can only be accessed within the block in which they are defined.

Consider the following code regarding let block scope:

let x = 1;
{ 
  let x = 2;
}
console.log(x); //1
Copy after login

In contrast, var declarations are not bound by block scope:

var x = 1;
{ 
  var x = 2;
}
console.log(x); //2
Copy after login

Another common problem is using asynchronous operations like setTimeout() in a loop. The following loop code will display the number 5 five times.

(function run(){
    for(var i=0; i<5; i++){
        setTimeout(function logValue(){
            console.log(i);         //5
        }, 100);
    }
})();
Copy after login

The for loop statement with the let declaration creates a new variable each time it loops and sets it to the block scope. The next loop of code will display 0 1 2 3 4 5.

(function run(){
  for(let i=0; i<5; i++){
    setTimeout(function log(){
      console.log(i); //0 1 2 3 4
    }, 100);
  }
})();
Copy after login

Lexical Scope

Lexical scope is the ability of an inner function to access the outer scope in which it is defined.

Look at this code:

(function autorun(){
    let x = 1;
    function log(){
      console.log(x);
    };
    
    function run(fn){
      let x = 100;
      fn();
    }
    
    run(log);//1
})();
Copy after login

log The function is a closure. It references the x variable from the parent function autorun(), not the x variable in the run() function.

A closure function has access to the scope in which it was created, not its own scope. The local function scope of

autorun() is the lexical scope of the log() function.

Scope Chain

Each scope has a link to the parent scope. When using variables, JavaScript looks down the scope chain until it finds the requested variable or reaches the global scope (i.e., the end of the scope chain).
Look at the following example:

let x0 = 0;
(function autorun1(){
 let x1 = 1;
  
 (function autorun2(){
   let x2 = 2;
  
   (function autorun3(){
     let x3 = 3;
      
     console.log(x0 + " " + x1 + " " + x2 + " " + x3);//0 1 2 3
    })();
  })();
})();
Copy after login

Internal function autorun3() can access local x3 variables. The variables x1 and x2 and the global variable x0 can also be accessed from external functions.

If the variable is not found, it will return an error in strict mode.

"use strict";
x = 1;
console.log(x)
//Uncaught ReferenceError: x is not defined
Copy after login

Non-strict mode is also called "sloppy mode", which creates a global variable hastily.

x = 1;
console.log(x); //1
Copy after login

Summary

Variables defined in the global scope can be used anywhere in the program.

In a module, variables declared outside functions are hidden and cannot be used in other modules unless they are explicitly exported.

Function scope means that parameters and variables defined in the function are visible anywhere in the function

Variables declared with let and const Has block scope. var does not have block scope.

【Related recommendations: JavaScript video tutorial

The above is the detailed content of Comprehensive analysis of JavaScript scope (with code). 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)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

There are several situations where this in js points to There are several situations where this in js points to May 06, 2024 pm 02:03 PM

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

See all articles