I'm a JS beginner. I'm trying to understand why calling fn() produces "undefined" when I use var to declare letVar and gives a ReferenceError when I use let to declare letVar.
Using var:
var letVar = "Outer";
function fn() {
console.log(letVar); // undefined
var letVar = "Inner";
}
fn();
Using let:
let letVar = "Outer";
function fn() {
console.log(letVar); // ReferenceError
let letVar = "Inner";
}
fn();
From my understanding, using var initializes letVar with a value of undefined when the program is compiled. However, when the program is executed, wouldn't letVar be assigned the value "Outer", meaning that fn() should produce "Outer"?
Furthermore, in the code that uses let, shouldn't console.log(letVar); have access to letVar = "Outer" because let letVar = "Outer"; is a global declaration & assignment? Thus, shouldn't calling fn() also produce "Outer"?
Thank you in advance :)