First, ECMAScript and JavaScript relationships:
ECMAScript is an internationally adopted standardized scripting language. JavaScript is composed of ECMAScript, DOM and BOM. It can be simply understood as: ECMAScript is the language specification of JavaScript, and JavaScript is the implementation and extension of ECMAScript.
1. Block scope {}
Scope in JS includes global scope and function scope. There is no concept of a block scope. Block level scope has been added to ECMAScript 6 (ES6 for short).
The block scope is included by {}, and {} in the if statement and for statement also belong to the block scope.
<script type="text/javascript"> { var a = 1; console.log(a); // 1 } console.log(a); // 1 // It can be seen that variables defined by var can be accessed across block scopes. (function A() { var b = 2; console.log(b); // 2 })(); // console.log(b); / / an error is reported, // It can be seen that variables defined by var cannot be accessed across function scopes if(true) { var c = 3; } console.log(c); // 3 for(var i = 0; i < 4; i ++) { var d = 5; }; console.log(i); // 4 (loop end i is already 4, so i here is 4) console.log(d); // 5 // The variables defined by var in if statement and for statement can be accessed outside, // It can be seen that if statement and for statement belong to block scope, not function scope. </script>
2. Differences among VaR, let and const
- var defined variables, without the concept of block, can be accessed across blocks, not across functions.
- The variables defined by let can only be accessed in block scope, not across blocks or functions.
- const is used to define constants. It must be initialized (i.e. it must be assigned) when it is used. It can only be accessed in the block scope and cannot be modified.
<script type="text/javascript"> // Block scope { var a = 1; let b = 2; const c = 3; // c = 4; / / error reported var aa; let bb; // const cc; / / error reported console.log(a); // 1 console.log(b); // 2 console.log(c); // 3 console.log(aa); // undefined console.log(bb); // undefined } console.log(a); // 1 // console.log(b); / / error reported // console.log(c); / / error reported // Function scope (function A() { var d = 5; let e = 6; const f = 7; console.log(d); // 5 console.log(e); // 6 (in the same {}, it belongs to the same block and can be accessed normally) console.log(f); // 7 (it belongs to the same block in the same {} and can be accessed normally) })(); // console.log(d); / / error reported // console.log(e); / / error reported // console.log(f); / / error reported </script>