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://www.walker-learn.xyz/archives/4308

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

Related Posts

  • 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.5K00
  • In-depth Understanding of ES6 007 [Study Notes]

    Set and Map Collections. In JS, there is an `in` operator that can determine if a property exists in an object without needing to read the object's value, returning true if it exists. However, the `in` operator also checks the object's prototype chain, so using this method is only relatively safe when the object's prototype is null. Set Collection: `let set = new Set()` `set.add(5)` `set.add("5")` `console.log(s…`

    Personal Mar 8, 2025
    1.3K00
  • In-depth Understanding of ES6 005 [Study Notes]

    Destructuring: Making data access more convenient. If you declare variables using `var`, `let`, or `const` with destructuring, you must provide an initializer (i.e., the value on the right side of the equals sign). The following will cause an error:
    // Syntax error `var {tyep,name}`
    // Syntax error `let {type,name}`
    // Syntax error `const {type,name}`
    To assign values to already declared variables using destructuring, consider the following:
    `let node = { type:&qu...`

    Personal Mar 8, 2025
    1.3K00
  • Go Engineer Comprehensive Course: protoc-gen-validate Study Notes

    protoc-gen-validate: Introduction and Usage Guide ✅ What is protoc-gen-validate? protoc-gen-validate (PGV for short) is a Protocol Buffers plugin used to add validation logic for struct fields in generated Go code. It automatically generates validation code for each field by adding validation rules in .proto files, saving you the trouble of manually...

    Personal Nov 25, 2025
    1.4K00
  • Node: In-depth Yet Easy to Understand (Shengsi Garden Education) 002 [Study Notes]

    Node's package management and loading mechanisms: npm search xxx, npm view xxx, npm install xxx. Node.js file system operation APIs: Node.js's `fs` module provides synchronous (Sync) and callback/Promise-based asynchronous APIs for operating on local files and directories. Commonly used capabilities in daily development include reading, writing, appending, deleting, traversing directories, listening for changes, and so on. The following examples are based on C...

    Personal Nov 24, 2025
    31900
EN
简体中文 繁體中文 English