eval()
The much-maligned eval()
function receives an upgrade in strict mode. The biggest change to eval()
is that it will no longer create variables or functions in the containing context. For example:
// eval() used to create a variable
// Non-strict mode: Alert displays 10
// Strict mode: Throws an ReferenceError when alert(x) is called
function doSomething(){
eval("let x = 10");
alert(x);
}
When run in nonstrict mode, this code creates a local variable x
in the function doSomething()
and that value is then displayed using alert()
. In strict mode, the call to eval()
does not create the variable x
inside of doSomething()
and so the call to alert()
throws a ReferenceError
because x
is undeclared.
Variables and functions can be declared inside of eval()
, but they remain inside a special scope that is used while code is being evaluated and then destroyed once completed. So the following code works without any errors:
"use strict";
let result = eval("let x ...