zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

94. what's the output and why? #150

Open goldEli opened 4 years ago

goldEli commented 4 years ago
function sayHi() {
  console.log(name);
  console.log(age);
  var name = "Lydia";
  let age = 21;
}

sayHi();
goldEli commented 4 years ago

输出结果: undefined Uncaught ReferenceError

zlx362211854 commented 4 years ago

所以先输出 undefined 再报错

nanslee commented 4 years ago

输出:

  1. undefined
  2. Uncaught ReferenceError

分析:

  1. 函数局部作用域内 var 变量声明提升
  2. let 产生块级作用域,变量声明按正常执行 以上代码执行变为:
    
    function sayHi() {
    var name;
    console.log(name);   // undefined
    console.log(age);   // Uncaught ReferenceError:age is not defined 
    name = "Lydia";
    let age = 21;
    }

sayHi();