eval() function allows to execute a string of code Minifiers badly work with eval() , do not use it
let code = 'alert("Hello")'
eval(code) // Hello
let value = eval('1+1')
value // 2
Eval’ed code is executed in the current lexical environment In strict mode, eval() has its own lexical environment
let a = 1
function f() {
let a = 2
eval('alert(a)')
}
f() // 2
'use strict'
eval("let x = 5; function f() {}")
alert(typeof x) // undefined
If eval’ed code doesn’t use outer variables, call eval() as window.eval()
let x = 1
{
let x = 5
window.eval('alert(x)') // 1 (global variable)
}
If eval’ed code needs local variables, change eval() to new Function() and pass them as arguments
let f = new Function('a', 'alert(a)')
f(5) // 5