JavaScript you don't know (Volume I) 4.11 let keyword continuation block scope summary

Posted by meshi on Tue, 08 Mar 2022 20:48:48 +0100

JavaScript you don't know (Volume I)

Chapter 3: let keywords

1. In Chapter 4, we will discuss promotion

Promotion means that a declaration is considered to exist in the entire scope of the scope in which it appears.
However, declarations made with let s are not promoted in the block scope. The declaration is not valid until the declared code is run
"Exist

{
console.log( bar ); //  ReferenceError!
let bar = 2;
}
  1. let can be used for garbage collection:

    Another reason why block scopes are very useful is related to closures and the recycling mechanism for recycling memory garbage. Here is a brief description
    The internal implementation principle, that is, the closure mechanism, will be explained in detail in Chapter 5.

function process(data) {
// Do something interesting here
}
var someReallyBigData = { .. };
process( someReallyBigData );

var btn = document.getElementById( "my_button" );
btn.addEventListener( "click", function click(evt) {
console.log("button clicked");
}, /*capturingPhase=*/false );

The click callback of the click function does not require the someReallyBigData variable. In theory, this means that when process(...) executes
After rows, data structures that occupy a lot of space in memory can be garbage collected. However, due to the click function
A closure covering the entire scope is provided, and the JavaScript engine most likely still retains this structure (depending on the specific situation)
Implementation).

This concern can be eliminated by saving the scope of bigrealdata clearly:

function process(data) {
	// Do something interesting here
} 
// The content defined in this block can be destroyed!
{
	let someReallyBigData = { .. };
	process( someReallyBigData );
}
var btn = document.getElementById( "my_button" );
btn.addEventListener( "click", function click(evt){
	console.log("button clicked");
}, /*capturingPhase=*/false );

3.let cycle:

A typical example of let taking advantage is the for loop discussed earlier.

for (let i=0; i<10; i++) {
	console.log( i );
}
console.log( i ); // ReferenceError

The let in the for loop header not only binds i to the block of the for loop, but in fact it rebinds it to each iteration of the loop to ensure that the value at the end of the previous loop iteration is used for re assignment. Here is another way to illustrate the rebinding behavior of each iteration:

{
    let j;
    for (j=0; j<10; j++) {
    let i = j; // Rebind each iteration!
    console.log( i );
    }
}

The reason for rebinding each iteration is very interesting, and we will explain it when we discuss closures in Chapter 5.

Pros and Cons: because the let declaration is attached to a new scope instead of the current function scope (and does not belong to the global scope),
When there are implicit dependencies on the var declaration in the function scope in the code, there will be many hidden traps
let to replace var requires extra effort in the process of code refactoring.

The following codes:

var foo = true, baz = 10;
if (foo) {
    var bar = 3;
    if (baz > bar) {
    console.log( baz );
    } 
    // ...
}

It can be reconstructed into the following equivalent form:

var foo = true, baz = 10;
if (foo) {
	var bar = 3;
	// ...
}
// 2 - 5 has changed
if (baz > bar) {
	console.log( baz );
}	

However, when using block level scoped variables, you need to pay attention to the following changes:

var foo = true, baz = 10;
if (foo) {
	let bar = 3;
	if (baz > bar) { // < -- don't forget bar when moving code!
		console.log( baz );
	}
}

4.const

In addition to let, ES6 also introduces const, which can also be used to create block scope variables, but its value is fixed
(constant). Any subsequent attempt to modify the value will cause an error.

The following examples can be well illustrated

var foo = true;
if (foo) {
    var a = 2;
    const b = 3; // Block scope constants contained in if
    a = 3; // Normal!
    b = 4; // Wrong!
} 
console.log( a ); // 3
console.log( b ); // ReferenceError!

5. Summary

Functions are the most common scope units in JavaScript. In essence, variables or functions declared inside a function will
"Hiding" in the scope is the design principle of good software.
But the function is not the only scope unit. Block scope means that variables and functions can not only belong to their scope,
It can also belong to a code block (usually within {...}).
Starting from ES3, try/catch structure has block scope in catch clause.
In ES6, let keyword (cousin of var keyword) is introduced to declare variables in any code block. if
(…) { let a = 2; } It will declare a variable that hijacks the {...} block of if and add the variable to the block
Yes.
Some people think that block scope should not be a complete alternative to function scope. The two functions should exist at the same time. Turn on
Developers can and should choose which scope to use according to their needs to create readable and maintainable good code.

Page 33 ~ Page 36 2021.04.11

Topics: Javascript