4

Came across this rule in ESLint and am not sure what the reasoning is behind. Is it faster? Less characters?

jconder
  • 686
  • 4
  • 9
James L.
  • 12,893
  • 4
  • 49
  • 60
  • Probably just because it's more readable and less verbose. – Barmar Oct 19 '17 at 00:08
  • 2
    Most of the defaults in JSLint are simply based on Crockford's personal preferences. – Barmar Oct 19 '17 at 00:09
  • It's also likely to be less error prone. – Barmar Oct 19 '17 at 00:09
  • Also, template literals will include literal newlines as part of the string, whereas in a normal string, you have to use `\n`. – CRice Oct 19 '17 at 00:11
  • 1
    Possible duplicate of [ES6 Template Literals Vs concatenated strings](https://stackoverflow.com/questions/27565056/es6-template-literals-vs-concatenated-strings) – Ken Y-N Oct 19 '17 at 00:12
  • When you concatenate many values it becomes way more readable with template literals. Also you never need to escape `'` or `"` – Isac Oct 19 '17 at 00:18
  • 2
    @Isac But you still need to escape `\``, ``\`` and `${` – Bergi Oct 19 '17 at 00:24
  • There are many rules in ESLint that are opinionated, some are even conflicting. That's why you can configure them. – Bergi Oct 19 '17 at 00:25
  • @Bergi That is true, however thoses cases are way less common than `'` or `"` – Isac Oct 19 '17 at 00:27
  • 1
    Generally the documentation page for each rule often explains the rationale for the rule. For the rule in question [here is the documentation page](https://eslint.org/docs/rules/prefer-template) – Ray Toal Oct 19 '17 at 00:31

1 Answers1

2

Depends on the string in question. By popular opinion this:

`Hello ${name}! It's a pleasure to greet you.`

is more readable than

'Hello ' + name + '! It\'s a pleasure to greet you.'

If there are no variables or single quotes then the difference is negligible.

Max Revine
  • 78
  • 6
  • Good answer. Looks like this question is a duplicate. There's more info here - https://stackoverflow.com/questions/27565056/es6-template-literals-vs-concatenated-strings – James L. Oct 19 '17 at 03:03
  • I do not believe it is a duplicate, and I'm trying to get the question re-opened so I can post a proper answer, but, in my best attempt yet to be concise: enforcing template literals instead of string concatenations prevents logic errors caused by string concatenations coercing math expressions into string expressions. e.g. ('5+5='+5+5) prints "5+5=55" instead of "5+5=10". This can be fixed by "guarding" the math expression: ('5+5='(5+5)) prints "5+5=10", but, ESLint cannot always enforce that guarding as it requires knowing the types. – jconder Oct 19 '17 at 03:13
  • However, since template literals do not overload the + operator, math expressions are implicitly guarded in them. Thus, by enforcing template literals over string concatenation, all such errors are eliminated. – jconder Oct 19 '17 at 03:15