let/const和var的区别

let/const和var的区别

var

  • 创建的变量没有作用域概念

  • 可以重新赋值,甚至重新声明

  • var声明的变量会存在变量提升

    • 原因是js在编译代码的阶段,会收集所有变量声明,并将这些变量声明提升至函数顶部,同时初始化值为undefined
//变量后边可以为一个基本类型数据
console.log(a) //undefined

var a = 10

console.log(a) // 10

//变量后边也可以为一个引用数据类型

console.log(a) //undefined

var a = function() {}

console.log(a) // 10

let/const

  • let和const是在es6之后出现的语法

    • let一般用来声明之后可能会改变的元素,可以被重新赋值
    • const一般用来声明一个常量,或者引用类型数据,不可以被重新赋值
  • 用这俩个声明的变量具有作用域

  • let和const是否有变量提升呢?

    • 在 TC39 github的解释变量提升只是民间的一种叫法

    let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

    • 通过这段话可以理解为let和const在创建变量的阶段有提升,但并未初始化,在初始化之前会有段暂时性死区。

你可能感兴趣的:(JavaScript,javascript,前端,ecmascript)