4

Consider the following code:

eval(".....;a=5;b=10;");
eval("a+b");

If in case here the 1st eval runs for long time, will my next eval return an error mentioning as a and b are undefined, as the a and b values are initialised at the end of 1st eval. Will the eval method run synchronously or asynchronously

Aruna
  • 11,959
  • 3
  • 28
  • 42
Shyam R
  • 473
  • 1
  • 5
  • 17

2 Answers2

2

eval is synchronous.

Lets look at this example:

console.log("before")
eval("console.log('eval')");
console.log("after");

You can see in that the print is in the order.

if it was asynchronous for example in this case:

console.log("before");
setTimeout(()=>console.log("asynchronous"),0)
console.log("after")

The asynchronous run after.

Alon
  • 2,919
  • 6
  • 27
  • 47
2

eval is synchronous in nature. But the evaluations/expressions inside the eval may have asynchronous code like setTimeout or setInterval.

For an instance.

Method 1: (synchronous example)

eval('var a=5, b=10;');
eval('console.log(a+b)');

Method 2: (asynchronous example)

eval('setInterval(function(){window["a"]=5, window["b"]=10;}, 1000)');
eval('console.log(typeof a)');

Note: Anyways, it's not recommended to use eval as mentioned in https://stackoverflow.com/a/86580/7055233

Community
  • 1
  • 1
Aruna
  • 11,959
  • 3
  • 28
  • 42