let
首先let是只在其声明的代码块中有效,如果在其他的代码块中是访问不到的
let num = 0;
function test() {
let num = 1;
}
test();
num // num=0
函数里面定义的只作用于函数内部
function test() {
let num = 1;
}
test();
num // num is not defined
如果要访问函数内部定义的,会直接报错,告诉你这个没有被定义
var
var定义的是一个全局的变量,存在着变量提升,也就是可以先使用后定义
在另一个代码块中也能访问到var定义的变量
var num = 1;
function test() {
num = 4;
}
test();
num // num=4
变量提升 没声明这个变量之前使用他,默认值是undefined
console.log(num); // undefined
var num = 4;
console.log(num); // 4
const
const声明的是一个常量,一旦被声明过后就不能被改变,也就是说在声明const变量时就要赋值给c他,const和let一样也是只作用于块之中
声明时不赋值
const s; // Missing initializer in const declaration
改变他的值时
const s = 5;
s = 4; // TypeError: Assignment to constant variable.