]>
Commit | Line | Data |
---|---|---|
8f9d1d4d DC |
1 | --- |
2 | title: prefer-template | |
8f9d1d4d DC |
3 | rule_type: suggestion |
4 | related_rules: | |
5 | - no-useless-concat | |
6 | - quotes | |
7 | --- | |
8 | ||
9 | ||
eb39fafa DC |
10 | |
11 | In ES2015 (ES6), we can use template literals instead of string concatenation. | |
12 | ||
13 | ```js | |
14 | var str = "Hello, " + name + "!"; | |
15 | ``` | |
16 | ||
17 | ```js | |
18 | /*eslint-env es6*/ | |
19 | ||
20 | var str = `Hello, ${name}!`; | |
21 | ``` | |
22 | ||
23 | ## Rule Details | |
24 | ||
25 | This rule is aimed to flag usage of `+` operators with strings. | |
26 | ||
27 | ## Examples | |
28 | ||
29 | Examples of **incorrect** code for this rule: | |
30 | ||
8f9d1d4d DC |
31 | ::: incorrect |
32 | ||
eb39fafa DC |
33 | ```js |
34 | /*eslint prefer-template: "error"*/ | |
35 | ||
36 | var str = "Hello, " + name + "!"; | |
37 | var str = "Time: " + (12 * 60 * 60 * 1000); | |
38 | ``` | |
39 | ||
8f9d1d4d DC |
40 | ::: |
41 | ||
eb39fafa DC |
42 | Examples of **correct** code for this rule: |
43 | ||
8f9d1d4d DC |
44 | ::: correct |
45 | ||
eb39fafa DC |
46 | ```js |
47 | /*eslint prefer-template: "error"*/ | |
48 | /*eslint-env es6*/ | |
49 | ||
50 | var str = "Hello World!"; | |
51 | var str = `Hello, ${name}!`; | |
52 | var str = `Time: ${12 * 60 * 60 * 1000}`; | |
53 | ||
54 | // This is reported by `no-useless-concat`. | |
55 | var str = "Hello, " + "World!"; | |
56 | ``` | |
57 | ||
8f9d1d4d DC |
58 | ::: |
59 | ||
eb39fafa DC |
60 | ## When Not To Use It |
61 | ||
62 | This rule should not be used in ES3/5 environments. | |
63 | ||
64 | In ES2015 (ES6) or later, if you don't want to be notified about string concatenation, you can safely disable this rule. |