[JavaScript] The difference and use between var, let, and const

1.var

  • var Repeatable declaration of variables
<script>
    var a = 6;
    var a = 8;
    consolog(a)  //8
</script>
  • var can be used at block level
<script>
      {
        var a = 66
      }
      console.log(a)  //66
</script>
  • var variable hoisting

The execution order of the first output a is equivalent to var a; console.log(a); a= 'apple'; In this way, the output result declares the variable a, but does not assign a value, so the result is undefined

The second output a declaration is assigned again so the result is apple

<script>
    console.log(a)  //undefined
    var a = 'apple';
    console.log(a)  //apple
</script>

2.let

  • let can not re-declare a variable
<script>
    let b = 6;
    let b = 8;
    consolog(b)  //Uncaught SyntaxError: Identifier 'b' has already been declared
                 //未捕获的语法错误: 标识符 b 已经被声明
</script>
  • let is not available at block level
<script>
      {
        let b = 88
      }
      console.log(b)  //Uncaught ReferenceError: b is not defined
                      //未获取 引用错误 b 未被定义
</script>
  • let does not have variable hoisting 
<script>
    console.log(b)  //ReferenceError: b is not defined
    let a = 'apple';
    console.log(b)  //apple
</script>

 3.const

  •  You must assign a value after the const declaration, otherwise an error will be reported
const  c = '51800';

console.log(c)  //51800


const d;  // SyntaxError: Missing initializer in const declaration 

          // 语法错误: const 声明中没有初始划
  • const constant means, if it has been defined, an error will be reported when modifying the constant
const c = 220
c = 330  //Uncaught TypeError: Assignment to constant variable. 
         //为抓取的 错误类型: 分配给的常量 变化了
console.log(c)


const aa = {
    a:456,
    b:789,
    c:123
}
aa.c = 4562456
aa.k =1234789
console.log(aa.k)  //1234789
//const只是保存了一个指向实际数据的指针,对于复杂对象类型
//(对象 object,数组 array,函数 function)数据结构变不变,const并无法控制
  • If const and let are used in the function, global variables cannot be used in it
var PI = "a";
if(true){
  console.log(PI);  // ReferenceError: PI is not defined,就算在外面的是let,都报错
  const PI = "3.1415926";
}

 

Guess you like

Origin blog.csdn.net/m0_56349322/article/details/123883475