Function vs eval
While working with eval
to do some hacky workarounds in build configuration, I was curious about the difference between eval
and Function
. Here is what I found.
Difference
Quoting from tc39/proposal-hashbang
:
Hashbang comments are only avilable at the start of a
Script
orModule
parsing goal. Sinceeval
usesScript
it does support Hashbang comments. SinceFunction
usesFunctionBody
, it does not.
eval
would execute the JavaScript code in the context of a module/script, while Function
would execute it in the context of a function.
This means that Function
would disallow hashbang comments, but allow the use of await
(unless using top-level await, then available in Script
also), and return
.
For making use of generators and async functions, there are seperate constructors for them:
GeneratorFunction
for generatorsAsyncFunction
for async functionsAsyncGeneratorFunction
for both
According to MDN, the Function
constructor also contains less security risks compared to eval
.