Home >Web Front-end >Front-end Q&A >Why don't you use var instead of let in es6?

Why don't you use var instead of let in es6?

WBOY
WBOYOriginal
2022-03-31 18:53:442808browse

Because var has no scope in if and for loops, the problem of referencing variables outside the scope can only be solved by using the scope of function; while let has block-level effects in if and for loops. Domain, this is a function that var does not have, so the let keyword is used in es6 instead of var.

Why don't you use var instead of let in es6?

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

Why not use var instead of let in es6

Because in previous JavaScript (before ES5), var has no scope in if and for loops, and can only be used with function Scope to solve the problem of referencing variables outside the scope

In ES6, let was added. It has block-level scope in if and for. Let has block-level scope. A {} is A scope, that is, let declares block-level variables, that is, local variables.

const also has a block-level scope. When our modified identifier does not want to be changed and assigned, use const

It is recommended to use const first in ES6 development, and only use let when you want to change an identifier

Note

  • 1.const cannot be modified after assignment

  • 2. Identifiers defined using const must be assigned a value

  • 3. The definition of a constant means that the object pointed to cannot be modified, but the properties of the object can be modified

Why dont you use var instead of let in es6?

#According to general logic, variables should be used after the declaration statement, but in the above code, the value of foo is output before the declaration, and This value is undefined, which means that the variable already exists before it is declared. Why does this problem occur when using var?

This is what people often call variable promotion, that is, variables can be used before declaration, and the value is undefined.

The variable bar declared by our console using let reported an error, which means that the variable bar did not exist before the declaration, and there is no variable promotion phenomenon here. In order to correct this phenomenon and allow everyone to better understand the code, the let command changes the grammatical behavior. The variables it uses must be used after declaration, otherwise an error will be reported.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Why don't you use var instead of let in es6?. 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