Home > Article > Web Front-end > What is the difference between let and var in js
The content of this article is about the difference between let and var in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1: Variable promotion or not
1: var:
console.log(a); // undefined var a = 'abc'; // 这段代码实际执行顺序是: var a; //变量声明提升至当前作用域顶部 console.log(a); a = 'abc';
2: let:
console.log(a); // 报错: a is not defined let a = 'abc'; // 这里, 用let声明变量, 变量声明不会提升, 完全按照文档流的执行顺序走
2: Scope problem
var:
for (var i = 0; i<10; i++) { // code.. } console.log(i); // 输出 10
2.let:
for (let i = 0; i<10; i++) { // code.. } console.log(i); // 报错: i is not defined // let 作用于 代码块 {}
The above is a complete introduction to the difference between let and var in js. If you want to know more about JavaScript tutorials, please pay attention to the PHP Chinese website.
The above is the detailed content of What is the difference between let and var in js. For more information, please follow other related articles on the PHP Chinese website!