let in ES6
let basic syntax
let 变量名 = 变量值
The difference between using let to create variables and using var to create variables
1. There is no variable promotion mechanism for let
console.log(str);//->undefined
console.log(num);//->Uncaught ReferenceError: num is not defined
console.log(avg);//undefined
console.log(sum);//Uncaught ReferenceError: num is not defined
var str = 'xxx';
let num = 12;
var avg = function () {
};
let sum = function () {
};
//=>es6中只提供了创建变量的新语法标准(let),创建函数还是沿用es5中的function(还会存在变量提升) 如果想让函数也不存在变量提升,都使用函数表达式赋值的方式操作:let fn = function (){};
//=>自执行函数
;(function(){
})();
//=>创建变量
let xxx = xxx;
//=>创建函数
let xxx = function(){};
//=>好处:此时代码中就不要在考虑变量提升了,只要这样处理,没有所谓的变量提升
2. Variables defined using let are not allowed
同一个作用域
in重复声明
var num = 12;
var num = 13;
console.log(num);//13
let str = 12;
let str = 13;
console.log(str);//Uncaught SyntaxError: Identifier 'str' has already been declared 当前报错,上面代码也不会执行(在js代码执行之前就已经知道有重复声明的了,也就是浏览器依然存在类似于变量提升的机制:在js代码执行之前先把所有let声明的变量过一遍,发现有重复的直接报错)
let num = 12,
fn = function () {
let num = 13;
}
console.log(num);// 12 当前作用域下别重复声明即可(不同作用域中的变量时自己私有的,名字重复没关系)
let num = 12;
num = 13;
console.log(num);//=>13 let 不允许重复声明 但是可以重复赋值
var att =100;
let att = 200;//Uncaught SyntaxError: Identifier 'att' has already been declared 不管你之前使用什么方式在当前作用域中声明的变量,再使用let声明的时候都会报错