let
1.没有预编译(预解析)环节,不存在变量提升。在代码块中,必须先定义再使用。
console.log(a); //undefined
var a = 6;
console.log(b); //报错 b is not defined
let b = 3;
2.同一作用域内不能重复定义变量
var a = 5;
var a = 12;
console.log(a); //12
let b = 5;
let b = 12;
console.log(b); // 报错 SyntaxError: Identifier 'b' has already been declared
3.for循环()里面是父级作用域,{}里面又是一个块级作用域
const
特性与let一样
注意点:
1.const定义变量不能修改
var a = 5;
a = 12;
console.log(a); //12
const b = 10;
b = 4;
console.log(b);//报错 TypeError: Assignment to constant variable.
2.const定义完变量必须有值,不能后赋值和修改
var a;
a = 12;
console.log(a); //12
const b;
b = 4;
console.log(b);//报错 SyntaxError: Missing initializer in const declaration
3.但是对象的一些方法可以使用
const arr = [1,2,3,4,5];
// arr = [1,3,5,7];
arr.push(1);
arr.pop();
arr.unshift(0);
arr.shift();
console.log(arr);