0

I've been studying for a job interview, and started digging into JavaScript. Came up with this.

So:

"use strict";

var x = 0;
var y = 0;

eval("x=3;y=11;"); //direct call to eval in global scope

console.log("x: " + x); // outputs 3
console.log("y: " + y); // outputs 11

But:

"use strict";

var x = 0;

(0, eval)("x=3;y=11;"); //indirect call to eval in global scope

console.log("x: " + x); // outputs 0 because the strict mode won't allow the reassignment? 
console.log("y: " + y); // outputs 11

I don't know/understand what happens with the x when the eval is executed. I know with strict mode off the assignment goes through no problem. Would anyone be willing to explain this to me? Thanks!

Donovan King
  • 855
  • 1
  • 6
  • 18

1 Answers1

0

It appears to be how Node.js handles variables (they do not default to global). The indirect call to eval is assigning to the global object.

"use strict";

var x = 0;

(0,eval)("x=3;y=11;");
x++;
console.log("x: " + x); // outputs 1
console.log("global x: " + global.x);  // outputs 3
console.log("y: " + y); // outputs 11
Donovan King
  • 855
  • 1
  • 6
  • 18