# Variables

TIP

A variable is “a named space in the memory” that stores values, it acts as a container for values in a program
Variable names are called identifiers

# var

  • The var keyword assigns a function scope to the variable
  • Variables declared using var do not support block level scope
    • if a variable is declared in a loop or if block it can be accessed outside the loop or the if block
    • var keyword support hoisting(状态提升)
    • 变量可以在声明前使用,因为提升到了作用域的顶端
  • If we declare the same variable twice using the var keyword within a block, the compiler will not throw an error

# let

  • ES6 defines a new variable scope —— The Block scope
  • allows the script to restrict access to the variable to the nearest enclosing { block }
  • let can't be re-declared
  function test() { 
   var num = 100;
   console.log(num); // 100
  //  {  let as block
      let num = 200 
      console.log(num)  // 200
  //  } 
} 
test();

# const

  • const declaration creates a read-only reference to a value
  • It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned
  • 其实最好用就是destructuring (解构)啦
   const {
          book: { name: bkname  },//取对象的内部因为重名就起个别名
          source: { name: sorname = {}} // apply a default to avoid undefined
        } = row
      console.log(bkname,sourname)

  • "constants" variable are immutable
  • reinitializing [array] will result in an error, but arr.push(..) is still ok ~
Last Updated: 2022/5/24 下午3:55:22