0

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 :)

nezza
  • 1
  • 1
  • No matter how you declare the variables, a variable declared inside a particular block will mean that all references to that variable name will refer to the variable declared in that block - and not an outer one. `let` variables can't be used before being initialized. – CertainPerformance May 04 '22 at 03:22

0 Answers0