]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-implied-eval.md
acfcfd5d230bab4127a989ebeb325f833170c47f
[pve-eslint.git] / eslint / docs / src / rules / no-implied-eval.md
1 ---
2 title: no-implied-eval
3 layout: doc
4 rule_type: suggestion
5 related_rules:
6 - no-eval
7 ---
8
9
10 It'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.
11
12 The 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:
13
14 ```js
15 setTimeout("alert('Hi!');", 100);
16 ```
17
18 This is considered an implied `eval()` because a string of JavaScript code is
19 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:
20
21 ```js
22 setTimeout(function() {
23 alert("Hi!");
24 }, 100);
25 ```
26
27 The best practice is to always use a function for the first argument of `setTimeout()` and `setInterval()` (and avoid `execScript()`).
28
29 ## Rule Details
30
31 This 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.
32
33 Examples of **incorrect** code for this rule:
34
35 ::: incorrect
36
37 ```js
38 /*eslint no-implied-eval: "error"*/
39
40 setTimeout("alert('Hi!');", 100);
41
42 setInterval("alert('Hi!');", 100);
43
44 execScript("alert('Hi!')");
45
46 window.setTimeout("count = 5", 10);
47
48 window.setInterval("foo = bar", 10);
49 ```
50
51 :::
52
53 Examples of **correct** code for this rule:
54
55 ::: correct
56
57 ```js
58 /*eslint no-implied-eval: "error"*/
59
60 setTimeout(function() {
61 alert("Hi!");
62 }, 100);
63
64 setInterval(function() {
65 alert("Hi!");
66 }, 100);
67 ```
68
69 :::
70
71 ## When Not To Use It
72
73 If you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule.