var
- 变量可以没有初始值 会报undefined但不会报错
- 变量可以修改
- 变量可以覆盖
(重复定义)
- 函数内重复定义对函数外无影响
- 函数内重新赋值对函数外有影响
var a = 1;
var b;
var c = 2;
console.log(a);//1
console.log(b);//undefined
console.log(c);//2
var c = 3 ;
console.log(c);//3
c = 4;
console.log(c);//4
k();
function k(){
var c = 5;
console.log(c);//5
c = 6;
console.log(c);//6
}
console.log(c);//4
m();
function m(){
c = 7;
}
console.log(c);//7
let
- 块级作用域
- 函数内外不影响 避免了全局变量的污染
- 没有得到广泛的支持
(Sublime Text 3 Nodejs 下 Run)
let a = 1;
let b;
let c = 2;
console.log(a);//1
console.log(b);//undefined
console.log(c);//2
let c = 3 ;//SyntaxError: Identifier 'c' has already been declared
c = 4;
console.log(c);//4
k();
function k(){
var c = 5;
console.log(c);//5
c = 6;
console.log(c);//6
}
console.log(c);//4
const
- 变量必须有初始值
- 变量值不可更改
- 变量值不可覆盖
const a = 1;
const b;//SyntaxError: missing = in const declaration
const c = 2;
console.log(a);//1
console.log(c);//2
const c = 3 ;//SyntaxError: redeclaration of const c
c = 4;//TypeError: invalid assignment to const `c'
k();
function k(){
const c = 5;
console.log(c);//5
}
console.log(c);//2
20170506补充
console.log(f);//ReferenceError: f is not defined
没有定义变量直接使用会报错
ReferenceError: f is not defined
console.log(f);//undefined
var f;
变量在使用之后才被定义 对于var来说 会发生变量提升
不会报错而是报没有定义
undefined
console.log(f);//ReferenceError: can't access lexical declaration `f' before initialization
let f;
而对于let的情况 回直接报错
ReferenceError: can't access lexical declaration `f' before initialization