One function gives different results in different consoles

Viewed 52

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

1 Answers

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"))
Related