let/const和var的区别
let/const和var的区别
var
//变量后边可以为一个基本类型数据
console.log(a) //undefinedvar a = 10console.log(a) // 10//变量后边也可以为一个引用数据类型console.log(a) //undefinedvar 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在创建变量的阶段有提升,但并未初始化,在初始化之前会有段暂时性死区。