Preface: Before learning about block-level scope, we need to have an understanding of scope. The so-called scope is the range within which a member in the code works. 1. What is block scope? The so-called block-level scope means that the variable can only be used in the code block or sub-code block where it is declared. There is no block-level scope in versions prior to /* * Block-level scope can only use the let keyword* The let keyword can not only declare block-level scope, but also can be used in global scope and function scope*/ // Global scope let a = 100; // Global variables (function () { // function scope let b = 200; // local variable })() if (true) { // block scope let c = 300; // local variable } console.log(a); // 100 console.log(b); // throws an exception console.log(c); // throws an exception 2. Why do we need block scope? Local variables may overwrite global variables var v = 100; (function(){ console.log(v); // undefined var v = 200; }) The variable used for counting in the loop body is leaked as a global variable // Define a loop body for (var v = 0; v < 10; v++) { console.log("This is a for loop"); // This is a for loop * 10 } console.log(v); // 10 If the variable is not released manually after the loop is completed, its life cycle will survive with the script and occupy memory. 3. With function declaration Case 1: if (true) { function f() {} } Case 2: try { function f() {} } catch(e) { // ... } The above two function declarations are illegal according to { function fun() { console.log('this is fun'); } } fun(); // this is fun // The above is equivalent to the following function { var fn = function () { console.log('this is fn'); } } fn(); // this is fn // If you use the let keyword, you cannot access it outside the block scope { let f = function () { console.log('this is f'); } } f(); // Throws an exception description of ReferenceError: f is not defined This is the end of this article about the new block-level scope feature of You may also be interested in:
|
<<: Introduction to commonly used fonts on the Web (fonts supported by iOS and Android browsers)
>>: Summary of @ usage in CSS (with examples and explanations)
by Take the effect shown in the picture as an exa...
MySQL variables include system variables and syst...
Table of contents 1. What are microtasks? 2. What...
Table of contents Preface difficulty Cross-domain...
Install Nginx on Docker Nginx is a high-performan...
Table of contents Basic description AST parsing R...
This tutorial shares the installation and configu...
Table of contents What utilities does VueUse have...
Table of contents Container Hierarchy The process...
Table of contents 1 Question 2 Methods 3 Experime...
This article introduces several methods of implem...
Limit input box to only pure numbers 1、onkeyup = ...
Reasons why the 1px line becomes thicker When wor...
1. Do a good job of cleaning before installation ...
This article introduces and shares the responsive...