# 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 afunction scope
to the variable - Variables declared using
var
donot
supportblock level scope
- if a variable is declared in a
loop
orif
block it can be accessedoutside
theloop
or theif
block var
keyword supporthoisting
(状态提升)- 变量可以在声明前使用,因为提升到了作用域的顶端
- if a variable is declared in a
- If we declare the same variable
twice
using thevar
keyword within a block, the compiler willnot
throw anerror
# let
ES6
defines a new variable scope ——The Block scope
- allows the script to
restrict
access to the variable to thenearest
enclosing{ block }
let
can't bere-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 aread-only
reference to a value- It does
not
mean the value it holds is immutable, just that the variable identifiercannot
bereassigned
- 其实最好用就是destructuring (解构)啦
const {
book: { name: bkname },//取对象的内部因为重名就起个别名
source: { name: sorname = {}} // apply a default to avoid undefined
} = row
console.log(bkname,sourname)
"constants"
variable areimmutable
- reinitializing
[array]
will result in an error, butarr.push(..)
is still ok ~