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)
Table of contents Data volume Anonymous and named...
This article shares with you two methods of setti...
Less is More is a catchphrase for many designers....
Table of contents background LIMIT Optimization O...
As the number of visits increases, the pressure o...
Preface Yesterday, there was a project that requi...
Problem phenomenon I recently used sysbench to te...
1. Introduction By enabling the slow query log, M...
1 Problem Description This article sorts the esta...
1. Demand A picture moves from left to right in a...
Table of contents environment summary Module Func...
Demand background Part of the data in the busines...
The installation method of MySQL5.7 rpm under Lin...
Alignment issues like type="radio" and t...
The command line mysqld –skip-grant-tables cannot...