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