Home > Web Front-end > JS Tutorial > What is the difference between let and var in js

What is the difference between let and var in js

云罗郡主
Release: 2018-11-24 16:34:01
forward
3685 people have browsed it

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.

What is the difference between let and var in js

1: Variable promotion or not

1: var:

console.log(a); // undefined
var a = 'abc';
// 这段代码实际执行顺序是:
var a;  //变量声明提升至当前作用域顶部
console.log(a);
a = 'abc';
Copy after login

2: let:

console.log(a); // 报错: a is not defined
let a = 'abc';
// 这里, 用let声明变量, 变量声明不会提升, 完全按照文档流的执行顺序走
Copy after login

2: Scope problem

  1. var:

for (var i = 0; i<10; i++) {    // code..  }
console.log(i); // 输出 10
Copy after login

2.let:

for (let i = 0; i<10; i++) {    // code..  }
console.log(i); // 报错: i is not defined
// let 作用于 代码块 {}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template