JavaScript

JavaScript

By DeepSource

Detected the use of an eval()-like method JS-0330

Bug risk

Executing JavaScript from an arbitrary string can greatly compromise your application's security. It is possible to achieve eval-like behaviour from incorrect use of the following functions: setTimeout(), setInterval(), setImmediate() and execScript() (Internet Explorer only). All of them are capable of accepting a string as their first argument and then interpreting it as JavaScript code in the global scope. This leaves your application vulnerable to several security threats.

setTimeout('alert("Hi!");', 100);

Using the Function constructor also has similar behavior, wherein it interprets a string as JavaScript code:

const fn = new Function('a', 'b', 'return a + b');

Bad Practice

setTimeout('alert("Hi!");', 100);
// or: 
execScript('alert("Hi!")');
// or: 
window.setInterval('foo = bar', 10);
// or: 
const callback = new Function('err', 'res', 'store(res.data);');

Recommended

setTimeout(function () {
  alert('Hi!');
}, 100);

execScript(function () {
  alert('Hi!');
});

const callback = (err, res) => {
  store(res.data);
}