Disable variable in eval

925 Views Asked by At

Is there a way to disable some variables for an eval?

var test = 'example';
eval('console.log(test)'); // here I would like test null
console.log(test); // here test should display 'example'
1

There are 1 best solutions below

2
On BEST ANSWER

Wrap your eval call inside an IIFE and shadow outer variables with local variables:

function doSeomthing() {
    var test = 'example';
    (function() {
        var test = null;
        eval('console.log(test)');
    })();
    console.log(test);
}

The eval code will only have access to the IIFE's local test, not the test declared inside of doSomething.

Note, however, that global variables cannot be shadowed in this way, since they will be accessible as properties of window or global. You could shadow window (or global) and deny access to all global variables as properties of window.