let和var关键字的区别
声明后未赋值,表现相同
(function() {
var varTest;
let letTest;
console.log(varTest); //输出undefined
console.log(letTest); //输出undefined
}());
使用未声明的变量,表现不同:
(function() {
console.log(varTest); //输出undefined
console.log(letTest); //直接报错:Uncaught ReferenceError: letTest is not defined
var varTest = 'OK';
let letTest = 'OK';
}());
重复声明同一个变量时,表现不同:
(function() {
var varTest = 'OK';
let letTest = 'OK';
var varTest = 'NO';
let letTest ='NO'; //直接报错:Uncaught SyntaxError: Identifier 'letTest' has already been declared
console.log(varTest); // 输出NO (注意要注释掉上面letTest变量的重复声明才能运行)
console.log(letTest); // 输出OK (注意要注释掉上面letTest变量的重复声明才能运行)
}());
变量作用范围,表现不同:
(function() {
var varTest = 'OK';
let letTest = 'OK';
{
var varTest = 'NO';
let letTest = 'NO';
}
console.log(varTest); // 输出"NO",内部"{}"中声明的varTest变量覆盖外部的letTest声明
console.log(letTest); // 输出"OK",内部"{}"中声明的letTest和外部的letTest不是同一个变量
}());