0

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.

King David
  • 13
  • 2

1 Answers1

3

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.

Jordan
  • 2,245
  • 6
  • 19
  • I'd wait for clarifications about what is supposed to be *"complains"* – Cid May 18 '21 at 16:16
  • He just clarified. It's what I thought he meant! – Jordan May 18 '21 at 16:17
  • Not really an error but it's what I figured he was talking about @Cid – Jordan May 18 '21 at 16:17
  • No worries. I've made a few edits so make sure you refresh to see the most recent version. If you've found this helpful, make sure to mark my answer as correct. Best of luck @KingDavid – Jordan May 18 '21 at 16:27
  • The bit that's the reason it won't work is because of `let` being scoped to eval. In essence, you can't access a variable using `let` outside of the block it was scoped in @KingDavid – Jordan May 18 '21 at 16:29