In-depth Understanding of ES6 001 [Study Notes]

Block-Level Scope Binding
Previously, `var` variable declarations, regardless of where they were declared, were considered to be declared at the top of their scope. Since functions are first-class citizens, the typical order was `function functionName()`, followed by `var variable`.

Block-Level Declarations
Block-level declarations are used to declare variables that cannot be accessed outside the scope of a specified block. Block-level scope exists in:
- Inside functions
- Within blocks (the region between `{` and `}`)

Temporal Dead Zone
When the JavaScript engine scans code and finds variable declarations, it either hoists them to the top of the scope...

Block-level Scope Binding

Previous variable declarations with var were considered to be declared at the top of the scope, regardless of where they were declared. Since functions are first-class citizens, the order is generally function functionName(), var variable.

Block Declarations

Block declarations are used to declare variables that are not accessible outside the scope of a given block. Block scope exists in:

  • Inside functions
  • Inside blocks (the area between characters and { and })

Temporal Dead Zone

When the JavaScript engine scans code and finds variable declarations, it either hoists them to the top of the scope or places them in the TDZ. Accessing variables in the TDZ will trigger a runtime error. Variables are only removed from the TDZ after their declaration has been executed, after which they can be accessed normally.

if(condition){
  console.log(typeof value) // 引用错误
  let value = "blue";
}
// 以下的value并不在TDZ中
console.log(typeof value); // "undefined"
if(condition){
  let value="blue"
}

Block-level Scope Binding in Loops

When using let, the variable only exists within the for loop. Once the loop ends, the variable cannot be accessed.

for(let i=0;i<10;i++){
  process(items[i]);
}
// i 在这里不可访问,抛出一个错误
console.log(i);

Functions in Loops

var declarations make it exceptionally difficult for developers to create functions within loops, because the variable remains accessible outside the loop.

var funs = [];
for(var i=0;i<10;i++){
  funs.push(function(){
    console.log(i)
  })
}
funcs.forEach(function(func){
  func(); // 输出10次数字10
})

To solve this problem, developers use Immediately Invoked Function Expressions (IIFEs) within loops to force the creation of copies of the counter variable. The IIFE creates a copy for each variable `i` it accepts and stores it as the variable `value`. The value of this variable is the value used by the function created in the corresponding iteration, thus calling each function.

var funs = [];
for(var i=0;i<10;i++){
  funs.push((function(value){
    return function(){
      console.log(i)
    }
  })(i))
}
funcs.forEach(function(func){
  func(); // 输出0,1,2...
})

let Declarations in Loops

let declarations simplify the looping process by mimicking everything described above. Each iteration of the loop creates a new variable and initializes it with the value of the variable of the same name from the previous iteration. This also applies to for-in, for-of, and for-each loops.

var funs = [];
for(let i=0;i<10;i++){
  funs.push(function(){
    console.log(i)
  })
}
funcs.forEach(function(func){
  func(); // 输出0,1,2...
})

It is crucial to understand that the behavior of `let` declarations within loops is specifically defined in the standard and is not necessarily related to `let`'s non-hoisting characteristic. In fact, early `let` implementations did not include this behavior; it was added later.

Using const in Loops

In for(const i=0;i<10;i++), an error will occur because i++ attempts to change the value of the constant `i`. However, in for-in and for-of loops, there is no operation that attempts to change the original value of `i`; instead, a new variable is created. Therefore, the execution will be the same as using a let declaration.

Global Scope Binding

Another difference between let and const and var is their behavior in the global scope. When `var` is used in the global scope, it creates a new global variable as a property of the global object. This means `var` is very likely to unintentionally overwrite an existing global variable. However, using let and const cannot overwrite global variables; they can only shadow them. So,

let RegExp = 'Hello world'
console.log(window.RegExp === RegExp)

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/4308

(0)
Walker的头像Walker
上一篇 Mar 8, 2025 10:59
下一篇 Mar 27, 2025 15:01

Related Posts

  • Go Engineer Comprehensive Course: Protobuf Guide [Study Notes]

    Protocol Buffers Getting Started Guide 1. Introduction Protocol Buffers (protobuf for short) is a language-agnostic, platform-agnostic, extensible structured data serialization mechanism developed by Google. Compared with serialization methods such as JSON and XML, protobuf is smaller, faster, and simpler. Project homepage: https://github.com/protocolbuffers/prot…

    Personal Nov 25, 2025
    1.2K00
  • In-depth Understanding of ES6 002 [Study Notes]

    Strings and Regular Expressions. Strings and Regular Expressions. JavaScript strings have always been built based on 16-bit character encoding (UTF-16). Each 16-bit sequence is a code unit, representing a character. String properties and methods like `length` and `charAt()` are all constructed based on these code units. The goal of Unicode is to provide a globally unique identifier for every character in the world. If we limit the character length to 16 bits, the number of code points will not...

    Personal Mar 8, 2025
    1.8K00
  • TS Everest 003 [Study Notes]

    Decorator // Decorator // Can only be used in classes (on the class itself, or class members) // Decorators, class decorators, property decorators, accessor decorators, parameter decorators //
    1. Type Decorator: Used to extend a class, or can also return a subclass. //
    First, `experimentalDecorators` must be enabled in `tsconfig.json`. `const classDecorator1 =

    Personal Mar 27, 2025
    1.4K00
  • Fearless forward, fist power unleashed.

    Striving is an attitude. Life is like a competition with no shortcuts; only through continuous training, breaking through, and surpassing oneself can one stand on their own stage. This is not merely a contest, but rather a self-awakening—daring to face the fight, daring to challenge, and daring to become a stronger version of oneself. The Spirit of Striving in Sports. Whether it's boxing, running, or strength training, every punch thrown, every bead of sweat, every moment of gritting one's teeth and persevering, is a tempering of both body and mind. Striving is not merely a confrontation, but an attitude—facing challenges without backing down; facing failure, ...

    Personal Feb 26, 2025
    1.3K00
  • Go Engineer Systematic Course 008 [Study Notes]

    Orders and Shopping Cart
    First, copy the service code framework of 'srv' from the inventory service, then find and replace the corresponding name (order_srv).

    Fundamentals of Encryption Technology
    Symmetric Encryption
    Principle:
    Uses the same key for encryption and decryption.
    Like a single key that can both lock and unlock a door.
    Fast encryption speed, suitable for large data transfers.
    Use cases:
    Local file encryption
    Database content encryption
    Content encryption during large data transfers
    Fast communication between internal systems...

    Personal Nov 25, 2025
    19500
EN
简体中文 繁體中文 English
欢迎🌹 Coding never stops, keep learning! 💡💻 光临🌹