It is well known that before ES5, the JavaScript language only had function scope and global scope. Using var to declare variables, variables declared with var also have variable promotion, which is confusing. Let’s first review ES5’s var declaration, and then compare let and const.
var
var declaration function scope and global scope.
Let’s take a look at the code:
function getName() { if (1 + 1 === 2) { var name = 'xixi'; } console.log(name); } getName();//xixi
In C or Java language, name should only be used in the if block, but it can also be accessed outside the if. This It is a manifestation that js does not have block-level scope. This drawback is very obvious in the for loop:
for (var i = 0; i < 10; i ++) { // ... } console.log(i);// 10
The original intention of var i is to declare a temporary variable i, used to traverse arrays, etc. It should not be accessed outside the for loop, but now it can When you were interviewed, did you say it was annoying or not? Better programmers will use immediate execution functions to simulate block-level scope. Originally, I would pay attention and try not to use the same variable name.
The above is the detailed content of Detailed explanation of ES6 block-level scope. For more information, please follow other related articles on the PHP Chinese website!