es6 随性学习之let,const与var的区别

时间:2022-07-26
本文章向大家介绍es6 随性学习之let,const与var的区别,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

ES6

var let const的区别

  • var 存在变量提升,而let,const不存在变量提升
  • 要了解三者的区别,首先应该了解变量提升
+ 什么是变量提升
    + 在javascript中,函数及变量声明都将被提升到函数的最顶部
    + 在javascript中,变量可以在使用前声明也可以在使用后声明 
  • 例1
    console.log(a); // undefind ===> a已经声明但是没有辅助
    var a = 100;
    console.log(b); // 报错:b is not defind 找不到变量
    let b = 200;
    console.log(c); // 报错:c is not defind 找不到变量
    const c = 300;
  • 例2
    function fun() {
        // 在else 中的声明变量 a 将提升到最顶部
        // console.log(a) // undefind 
        // console.log(b) // b is not defined
        // console.log(c) // c is not defined
        if(true) {
            console.log(a) 
            console.log(b) // ReferenceError: Cannot access 'b' before initialization 不能在变量声明前使用 b
            console.log(c) // ReferenceError: Cannot access 'c' before initialization 不能在变量声明前使用 c
            var a = 1;
            let b = 2;
            const c = 3;
            console.log(a) // 1
        }
    }
    console.log(a) // ReferenceError: a is not defined 变量提升不会突破函数内部
  • let,const都是块级局部变量
{
    let a = 1;
    // 变量 a 超出大括号将使用将报错
}
console.log(a) // a is not defined 

// const 与 let 一样 区别在于 const 在声明时就需要赋值
const b // 报错:SyntaxError: Missing initializer in const declaration
// 另外不同的是 const 赋值后 再次赋值将报错
const c = 100
c = 200

const num = 1;
num.b = 2; // 不会报错 num.b 的值也无法访问
console.log(num.b) // undefined
  • 而同一作用域下 let, const 不能声明同名变量,而var可以
const a = 2
const a = 1
// Identifier 'a' has already been declared 变量 a 已经被声明