javascriptscopelexical-scope

Why does the second code snippet give an error but the first one runs fine for JS?


I am learning about Lexical Environments in JavaScript and came across this error. Code snippet with error:

let x = 1;

function func() {
  console.log(x); 
  let x = 2;
}

func();

But this code runs correctly:

let x = 1;

function func() {
  console.log(x);
}

func(); //logs out 1

I expected the first code snippet to log the value 1, and then give the error that x has already been declared but instead it gives me a reference error for the console.log(x) section.


Solution

  • The issue is related to hoisting in JavaScript. The let keyword is block-scoped and is hoisted to the top of the block but not initialized. In the first code snippet, console.log(x) is encountering the variable x before it is declared and initialized within the block, resulting in a ReferenceError. In the second code snippet, the variable x is declared and initialized before the console.log(x) statement, avoiding the error.

    let x = 1;
    function func() {
      let x = 2;
      console.log(x);
    }
    func();