2

I am new to JS, and currently study using Eloquent JS Book. In ch 10 there was a function below. When i run it on localhost with live server, the output is 1 for both logs. However when using the console given by the book or other sandbox js consoles I found online, the output is 2 and 1. If you know why, please help

const x = 1;
function evalAndReturnX(code) {
  eval(code);
  return x;
}

console.log(evalAndReturnX("var x = 2"));
// → 2
console.log(x);
// → 1
platonkoby
  • 23
  • 3
  • `eval` is definitely synchronous -> https://stackoverflow.com/questions/40968060/is-javascript-eval-synchronous-or-asynchronous. Which server are you running with locally? – meteor Oct 31 '20 at 02:59
  • 1
    In strict mode, `eval` will create a new scope for declarations. – Bergi Oct 31 '20 at 04:49

1 Answers1

3

The difference between those environments would be strict mode. Only in sloppy mode, eval is allowed to declare new variables in the function scope.

"use strict"; /*
^^^^^^^^^^^^^ */
const x = 1;
function evalAndReturnX(code) {
  eval(code);
  return x;
}

console.log(evalAndReturnX("var x = 2")); // → 1, as it should be
console.log(x); // → 1

If you want to get 2 even in strict mode, I'd suggest you either do

var x;
eval("x = 2");
console.log(x);

or

console.log(eval("var x = 2" + "; x"))
Bergi
  • 630,263
  • 148
  • 957
  • 1,375