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

  • A+
Category:Languages

This question already has an answer here:

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

On a side note : the strict mode prevents eval from declaring a variable outside of its scope (see snippet).

function strictFoo(str, a) { "use strict";   eval( str );   console.log( a, c ); }  function foo(str, a) {   eval( str );   console.log( a, b ); }  foo( "var b = 3;", 1 );  strictFoo( "var c = 3;", 1 );

EDIT Regarding the marking as duplicate. I'm not really sure eval("let b=1"); enables strict mode. See the snippet below.

I'm using eval to execute code that's not executable in strict mode (the with keyword is forbidden in strict mode). And it doesn't throw any error.

eval(` (function() { var maison = {}; maison.prix = 1000; var prix = 200;  with (maison) {   console.log(maison.prix); } })() `);  eval(`let b = 10; (function() {  var maison = {}; maison.prix = 1000; var prix = 200;  with (maison) {   console.log(maison.prix); } })() `);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: