search
HomeWeb Front-endJS TutorialComprehensive analysis of JavaScript scope (with code)

Comprehensive analysis of JavaScript scope (with code)

Apr 03, 2019 am 10:27 AM
javascriptScopefront 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);

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 };

This way the GLOBAL_DATA variable will be everywhere .

console.log(GLOBAL_DATA)

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 };

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

import { sequence, toList, toList } from "./sequence";

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

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

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

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();

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

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

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

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

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<p>The <code>for</code> loop statement with the <code>let</code> declaration creates a new variable each time it loops and sets it to the block scope. The next loop of code will display <code>0 1 2 3 4 5</code>. </p><pre class="brush:php;toolbar:false">(function run(){
  for(let i=0; i<h3 id="Lexical-Scope"> Lexical Scope </h3><p> Lexical scope is the ability of an inner function to access the outer scope in which it is defined. </p><p>Look at this code: </p><pre class="brush:php;toolbar:false">(function autorun(){
    let x = 1;
    function log(){
      console.log(x);
    };
    
    function run(fn){
      let x = 100;
      fn();
    }
    
    run(log);//1
})();

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
    })();
  })();
})();

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

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

x = 1;
console.log(x); //1

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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version