eval() Function Is Limited by Lightning Locker
In Lightning Locker, use of the
eval() function is supported to enable use of third-party libraries that evaluate code dynamically. However, it’s limited to work only in the global scope of the namespace. The
eval() function can’t access the local variables within the scope in which it’s called.
eval() has two modes of execution. When you invoke
eval() directly, it works in the local scope. When you invoke it via a reference, it works in the global scope. Lightning Locker only supports the latter.
For example, suppose that you execute the following code:
A call to
bar() returns 2 when evaluation is performed in the local scope, and returns 1 when it’s performed in the global scope. If you must use variables from the local scope, refactor your code. Use a
Function(), declare the local variables as parameters, pass them as arguments, and add a return statement:
Lightning Web Security doesn’t limit
eval() to the global scope because the code executes in a sandbox. However, invoking
eval() directly in local scope is still not recommended.