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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With