公共特性

1. 无变量声明提升

  1. console.log(a) // undefined
  2. var a = 123
  1. console.log(a) // ReferenceError: a is not defined.
  2. const a = 123

2. 不能重复声明

  1. var a = 123
  2. const a = 123 // Uncaught SyntaxError: Identifier 'a' has already been declare
  1. const a = 123
  2. const a = 123 // Uncaught SyntaxError: Identifier 'a' has already been declare

3. 块级作用域

概念

  • 任何一对花括号({和})中的语句集都属于一个块,在这之中定义的所有变量在代码块外都是不可见的

    1. {
    2. var a = 123
    3. }
    4. console.log(a) // 123
    1. {
    2. const a = 123
    3. }
    4. console.log(a) // ReferenceError: a is not defined.

    4. 暂时性死区

    概念

  • 代码块内,使用 let 命令声明变量之前,该变量都是不可用的

    作用

  • 为了减少运行时错误,防止在变量声明前就使用这个变量,从而导致意料之外的行为 ```javascript var tmp = 123;

if (true) { tmp = ‘abc’; // ReferenceError let tmp; }

  1. <a name="t0t9o"></a>
  2. # 5. 不会挂载到顶层对象 window
  3. ```javascript
  4. var a = 123
  5. console.log(window.a) // 123
  1. const b = 123
  2. console.log(window.b) // undefined

const

  1. 在声明时必须赋值
  2. 如果是常量,值永远不能改变
  3. 如果是变量,变量的地址不能改变

    let

  4. 声明时不用赋值,