]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/no-implied-eval.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-implied-eval.md
CommitLineData
8f9d1d4d
DC
1---
2title: no-implied-eval
8f9d1d4d
DC
3rule_type: suggestion
4related_rules:
5- no-eval
6---
7
eb39fafa
DC
8
9It's considered a good practice to avoid using `eval()` in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing `eval()`. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.
10
11The first is using `setTimeout()`, `setInterval()` or `execScript()` (Internet Explorer only), all of which can accept a string of JavaScript code as their first argument. For example:
12
13```js
14setTimeout("alert('Hi!');", 100);
15```
16
17This is considered an implied `eval()` because a string of JavaScript code is
18 passed in to be interpreted. The same can be done with `setInterval()` and `execScript()`. Both interpret the JavaScript code in the global scope. For both `setTimeout()` and `setInterval()`, the first argument can also be a function, and that is considered safer and is more performant:
19
20```js
21setTimeout(function() {
22 alert("Hi!");
23}, 100);
24```
25
26The best practice is to always use a function for the first argument of `setTimeout()` and `setInterval()` (and avoid `execScript()`).
27
eb39fafa
DC
28## Rule Details
29
30This rule aims to eliminate implied `eval()` through the use of `setTimeout()`, `setInterval()` or `execScript()`. As such, it will warn when either function is used with a string as the first argument.
31
32Examples of **incorrect** code for this rule:
33
8f9d1d4d
DC
34::: incorrect
35
eb39fafa
DC
36```js
37/*eslint no-implied-eval: "error"*/
38
39setTimeout("alert('Hi!');", 100);
40
41setInterval("alert('Hi!');", 100);
42
43execScript("alert('Hi!')");
44
45window.setTimeout("count = 5", 10);
46
47window.setInterval("foo = bar", 10);
48```
49
8f9d1d4d
DC
50:::
51
eb39fafa
DC
52Examples of **correct** code for this rule:
53
8f9d1d4d
DC
54::: correct
55
eb39fafa
DC
56```js
57/*eslint no-implied-eval: "error"*/
58
59setTimeout(function() {
60 alert("Hi!");
61}, 100);
62
63setInterval(function() {
64 alert("Hi!");
65}, 100);
66```
67
8f9d1d4d
DC
68:::
69
eb39fafa
DC
70## When Not To Use It
71
72If you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule.