Get the App
SLTechnology News&Howtos  ›  Development  › 

JavaScript block scope, methods for redeclaring variables

Shulou Source: shulou.com Published: 2022-06-01 05:16:27 09月25日 Update

This article mainly introduces the JavaScript block scope, re-declaration of variable method related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this JavaScript block scope, re-declaration of variable method article will have a harvest, let's take a look.

JavaScript block scope

Variables declared by the var keyword have no block scope.

Variables declared within block {} can be accessed from outside the block.

Example

{

Var x = 10

}

/ / you can use x here

Before ES2015, JavaScript had no block scope.

Variables with block scope can be declared using the let keyword.

Variables declared within block {} cannot be accessed from outside the block:

Example

{

Let x = 10

}

/ / you cannot use x here

Redeclare variables

Redeclaring variables using the var keyword can cause problems.

Redeclaring variables in a block also redeclares variables outside the block:

Example

Var x = 10

/ / here x is 10

{

Var x = 6

/ / here x is 6

}

/ / here x is 6

Try it yourself.

Redeclaring variables using the let keyword solves this problem.

Redeclaring variables in a block does not redeclare variables outside the block:

Example

Var x = 10

/ / here x is 10

{

Let x = 6

/ / here x is 6

}

/ / here x is 10

This is the end of this article on "JavaScript block scope, methods for redeclaring variables". Thank you for reading! I believe you all have a certain understanding of the knowledge of "JavaScript block scope and the method of redeclaring variables". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Variables functions methods keys examples knowledge keywords keywords content articles questions values easy to operate articles easy to understand more look industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Technology OPPO Reno Microsoft Shulou Information