Home >Web Front-end >JS Tutorial >Detailed explanation of ES6 block-level scope

Detailed explanation of ES6 block-level scope

小云云
小云云Original
2018-01-26 16:45:571594browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn