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

45 views Asked by At

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.

2

There are 2 answers

0
Hashir Khan On BEST ANSWER

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();
1
Ibrahima Dansoko On

In the first code snippet, the error occurs because JavaScript does not allow accessing a let variable before it's declared within the same block. In func(), you're trying to use x before its declaration with let, which causes an error. In the second snippet, there's no let declaration of x inside func, so the outer x is used without any issue.