Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why let keyword does not work with eval() [duplicate]

Tags:

javascript

function foo(str, a) {
  eval( str );
  console.log( a, b );
}

foo( "var b = 3;", 1 ); 

This works just fine, but when we use let instead of var, it does not work. Why?

like image 236
Kenny Omega Avatar asked Apr 30 '18 10:04

Kenny Omega


1 Answers

Because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code, since var declares a variable in the function scope.

let, on the other hand, declares a variable in a block scope. So, your b variable will only be visible in your eval block. It's not visible in your function's scope.

More on the differences between var and let

EDIT : To be more precise eval + let do, in fact, create a Lexical Environment. See @RobG response in Define const variable using eval()

like image 101
Guillaume Georges Avatar answered Oct 02 '22 17:10

Guillaume Georges