Home  >  Article  >  Web Front-end  >  What is the difference between the usage of let and var in JavaScript?

What is the difference between the usage of let and var in JavaScript?

不言
不言Original
2019-01-19 16:36:493305browse

Let in What is the difference between the usage of let and var in JavaScript? is used to limit the scope of variables to blocks. If you use var to declare a variable, the scope will be in function units. In this article, we will introduce the specific differences between let and var in What is the difference between the usage of let and var in JavaScript?. Below we Let’s look at the specific content.

What is the difference between the usage of let and var in JavaScript?

Here we first talk about how to use let.

let is used when declaring variables.

Let’s look at the following code

let num = 123;
console.log(num);
{
    let num = 456;
    console.log(num);
}
console.log(num);

The execution results are as follows

123
456
123

According to the above execution results, we can confirm that the scope of the variable is limited to the block.

Next let’s look at the difference between the use of var and the above use of let

var is the variable scope in the function

Let’s look at the following code

var num = 123;
console.log(num);
{
    var num = 456;
    console.log(num);
}
console.log(num);

Execution results

123
456
456

According to the above execution results we can confirm that the scope of the variable is outside the block.

This article ends here. For more exciting content, you can pay attention to the relevant column tutorials on the php Chinese website! ! !

The above is the detailed content of What is the difference between the usage of let and var in JavaScript?. 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