search
HomeWeb Front-endJS TutorialClarify the lexical, static, dynamic, function, and block scopes in JS

Well, I just wrote a lot, but it was overwritten by my mistake. My hard work╥﹏╥…

It’s okay to write it again. I also remind you to blog on this platform and be like me. For students who also like to use markdown language to code words
"Save online to draft" is a good habit, hmm
Today is Double Eleven, I feel like it’s time to buy something. .


When many students learn JavaScript, they may hear about "various" scopes
What are lexical scope, static scope, dynamic scope, function scope, Block scope
I can’t tell the difference
Let me clarify my thoughts for everyone

Scope mode

The scope’s working mode is divided into two types, static function Domain and dynamic scope
Static scope includes function scope and block scope
Students may ask what about lexical scope
In fact, lexical scope and static scope are the same thing

Clarify the lexical, static, dynamic, function, and block scopes in JS

The picture is not good, everyone understands what I mean
Now that we have clarified this point, let’s go into detail

There is one more question to add, That is, is there dynamic scope in JavaScript?
Regarding this, I got completely opposite answers in the two books I have read

Whether it is the with statement or the catch clause of the try-catch statement, or it contains The eval() functions are all considered dynamic scopes. Dynamic scope only exists during code execution and therefore cannot be detected by static analysis (looking at the code structure). ——"High-Performance JavaScript" /p24

What needs to be clear is that in fact JavaScript does not have dynamic scope. It has only lexical scope, plain and simple. But this mechanism is somewhat like dynamic scope. ——"JavaScript You Don't Know (Volume 1)" /p59

These two books are very new, and both are very authoritative books, highly recommended
especially "JavaScript You Don't Know" series, when the middle volume just came out last month, I couldn't wait to buy a copy from the Internet
I was not disappointed
Ahem, I digressed, back to the topic
I think the great authors of the original book have different understandings of dynamic scope
That’s why this seemingly contradictory point of view
Here I want to talk about my position
Through my understanding, I also think There is no dynamic scope in JavaScript
What is the difference between static and dynamic scope
Look down↓

Lexical scope and dynamic scope

Let me start with a piece of code

function foo(){
    var a = 1;
    bar();
}function bar(){
    console.log(a);
}var a = 100;
foo();

Through our in-depth understanding of precompilation and scope
In the lexical scope of our JavaScript, the final result prints 100

But if we If the scope is a dynamic scope, the printed value will become 1
Why is this?
The most important feature of lexical scope is that its definition process occurs during the writing phase (if eval() and with are not used)
Dynamic scope enables the scope to be dynamically determined at runtime

Lexical scope cares about where the function is declared, and the scope chain is based on scope nesting
Dynamic scope cares about where the function is called, and the scope chain is based on the call stack

I translated the above words to The code is
Lexical scope: Because the bar function is declared globally, I output the value of the global variable a
Dynamic scope: Because the bar function is called within the foo function, so I output foo The value of variable a in
This is my understanding

The programming languages ​​I have come into contact with are limited, all of which are lexical scopes. I have never seen a language based on dynamic scopes
C, C++, C#, Java, JavaScript, and php are all lexical scopes
JavaScript and php are based on function scope, and others are based on block scope

Function scope and block scope

In my understanding
The function scope is the scope generated by the function code block, and the block scope is the scope generated by the curly bracket code block
I have seen this written in many blogs. In JavaScript, there is only Function scope (big mistake)
This is completely incorrect, there is no dispute
JavaScript is indeed based on function scope, but it does not mean that we do not have block scope
There are many special cases, There are the with keyword, the catch clause of the try-catch statement, the let keyword (ES6), and the const keyword (ES6)
Here I will just briefly talk about it
Both the keyword with and the catch clause can be generated Block scope
I should have written about this in detail in an article
If you are interested, you can check it out
Portal->JavaScript deceptive lexical eval, with and catch and its performance issues

The let keyword is very similar to var. They both declare variables. However, the let keyword can bind the variable to any scope.
And using let to declare will not be promoted in the block scope.
The const keyword also declares variables, but it declares constants and binds variables to the block scope.
This is almost the same as our const keyword in C/C++
More about me I’ll talk about it in detail later when I write about ES6 knowledge
Now we only need to know “There is a block scope in JavaScript

Summary

As usual, let me summarize for you

  • Scope working mode: Lexical/static scope, dynamic scope

  • Lexical scope : Function scope, block scope

  • JavaScript does not have dynamic scope

  • JavaScript has block scope

  • with, catch clause, let (ES6), const (ES6) generate block scope

  • Lexical scope cares where the function is declared

  • Dynamic scope cares about where the function is called

  • Lexical scope scope chaining is based on scope nesting

  • Dynamic scope scope chain is based on the call stack

The above is to clarify the content of lexical, static, dynamic, function, and block scope in JS. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!


Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!