Search code examples
javascriptnode.jseval

Javascript Why can't use let inside eval()


I would like someone to please tell me why Javascript does not complain when I do this:

    eval("x = 1");
    console.log(x);

output: 1

...However, it complains if I do this:

    eval("let x=1");
    console.log(x);

output:
> ReferenceError: x is not defined

Thank you. Note: I know using eval is bad, serious security risks, blah,blah, thank you for that. I just want to understand the theory behind this.


Solution

  • Edit: Now that you've updated your question, I can help a little more specifically.

    The reason

    eval("let x = 1");
    console.log(x);
    

    doesn't work is because let is local to its scope. You cannot access the variable outside of the scope of eval.

    You would need to use var to make the variable globally accessible.

    To quote MDN:

    let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

    The reason your original, unedited question didn't work was because you were assigning the variable without actually doing anything with it.

    eval("var x = 1"); // Undefined
    eval("const x = 1"); // Undefined
    eval("let x = 1"); // Undefined
    

    Now if you give it something to spit back out:

    eval("var x = 1; x"); // 1
    eval("const x = 1; x"); // 1
    eval("let x = 1; x"); // 1
    

    At least that's the way it works in my chromium console.

    The way I see it is that in the first example you're simply evaluating the response of the statement x = 1.

    However, it doesn't return a response when evaluating because there is no response to return.

    It's just an assignment. You are telling the eval that there is this variable called x and you are telling it that it has a value of 1 but you are not telling it what to do with that variable.

    It is the equivalent of you creating the following:

    doNothing.js

    let x = 1;
    

    If you run this program, it will not output anything to the console because all it is doing is assigning a value to x.