]>
Commit | Line | Data |
---|---|---|
8f9d1d4d DC |
1 | --- |
2 | title: no-implied-eval | |
8f9d1d4d DC |
3 | rule_type: suggestion |
4 | related_rules: | |
5 | - no-eval | |
6 | --- | |
7 | ||
eb39fafa DC |
8 | |
9 | 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. | |
10 | ||
11 | 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: | |
12 | ||
13 | ```js | |
14 | setTimeout("alert('Hi!');", 100); | |
15 | ``` | |
16 | ||
17 | This 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 | |
21 | setTimeout(function() { | |
22 | alert("Hi!"); | |
23 | }, 100); | |
24 | ``` | |
25 | ||
26 | The 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 | ||
30 | 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. | |
31 | ||
32 | Examples of **incorrect** code for this rule: | |
33 | ||
8f9d1d4d DC |
34 | ::: incorrect |
35 | ||
eb39fafa DC |
36 | ```js |
37 | /*eslint no-implied-eval: "error"*/ | |
38 | ||
39 | setTimeout("alert('Hi!');", 100); | |
40 | ||
41 | setInterval("alert('Hi!');", 100); | |
42 | ||
43 | execScript("alert('Hi!')"); | |
44 | ||
45 | window.setTimeout("count = 5", 10); | |
46 | ||
47 | window.setInterval("foo = bar", 10); | |
48 | ``` | |
49 | ||
8f9d1d4d DC |
50 | ::: |
51 | ||
eb39fafa DC |
52 | Examples of **correct** code for this rule: |
53 | ||
8f9d1d4d DC |
54 | ::: correct |
55 | ||
eb39fafa DC |
56 | ```js |
57 | /*eslint no-implied-eval: "error"*/ | |
58 | ||
59 | setTimeout(function() { | |
60 | alert("Hi!"); | |
61 | }, 100); | |
62 | ||
63 | setInterval(function() { | |
64 | alert("Hi!"); | |
65 | }, 100); | |
66 | ``` | |
67 | ||
8f9d1d4d DC |
68 | ::: |
69 | ||
eb39fafa DC |
70 | ## When Not To Use It |
71 | ||
72 | If you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule. |