Can JavaScript variables be used before declaration?
This article mainly introduces the JavaScript variable can be used before the declaration of the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that after reading this JavaScript variable can be used before the declaration of the article will have a harvest, let's take a look at it.
The JavaScript var variable is allowed to be redeclared anywhere in the program:
Example
Var x = 2; / / allow
Var x = 3; / / allow
X = 4; / / allow
It is not allowed to redeclare or reassign existing var or let variables to const in the same scope or block:
Example
Var x = 2; / / allow
Const x = 2; / / not allowed
{
Let x = 2; / / allow
Const x = 2; / / not allowed
}
It is not allowed to redeclare or assign an existing const variable in the same scope or block:
Example
Const x = 2; / / allow
Const x = 3; / / not allowed
X = 3; / / not allowed
Var x = 3; / / not allowed
Let x = 3; / / not allowed
{
Const x = 2; / / allow
Const x = 3; / / not allowed
X = 3; / / not allowed
Var x = 3; / / not allowed
Let x = 3; / / not allowed
}
It is allowed to redeclare const in another scope or block:
Example
Const x = 2; / / allow
{
Const x = 3; / / allow
}
{
Const x = 4; / / allow
}
Promote
Variables defined by var are promoted to the top. If you do not know what Hoisting is, please learn this chapter.
You can use it before declaring the var variable:
Example
CarName = "Volvo"; / / you can use carName here
Var carName
Variables defined by const are not promoted to the top.
The const variable cannot be used before declaration:
Example
CarName = "Volvo"; / / you cannot use carName here
Const carName = "Volvo"
This is the end of the article on "can JavaScript variables be used before declaration?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "can JavaScript variables be used before declaration". If you want to learn more, you are welcome to follow the industry information channel.