在使用var 声明变量时,如果变量名之前打印该变量,输出的结果是undefined,这是因为js在编译过程中,会先检测变量名和函数,此时变量名被提升到函数的顶部,但是还没有给此变量赋值,使用打印出undefined
function fn() {
console.log(name) //undefined
var name = 'xxx'
}
而在使用es6中的const 声明变量,控制台则会报错
console.log('names', name2)
const name2 = 'xiao'
Uncaught ReferenceError: Cannot access 'name2' before initialization