let/const和var的区别

var创建的变量无作用域,可重新赋值且存在变量提升。let和const在ES6中引入,它们有块级作用域。let可重赋值,const不可变,用于声明常量。let和const在创建时提升但未初始化,存在暂时性死区。
摘要由CSDN通过智能技术生成

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在创建变量的阶段有提升,但并未初始化,在初始化之前会有段暂时性死区。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值