2

With the introduction of template literals for JavaScript, it has much advantage over single quote and double quote as per mentioned in https://ponyfoo.com/articles/template-literals-strictly-better-strings.

In term of performance, there's no obvious different between them as stated in https://medium.com/javascript-in-plain-english/are-backticks-slower-than-other-strings-in-javascript-ce4abf9b9fa

So my question is, is there any case where template literals can't be used other than the case of printing "Testing ${something}" where then back-tick need a slash as in `Testing \${something}`

I have checked various related existing Stackoverflow

From the stackoverflows, can't see anything that shows a single quote or double quote is required that can't be achieved by backtick, other than stating it as easier distinguish the different purpose.

Elye
  • 53,639
  • 54
  • 212
  • 474
  • Hi @CertainPerformance, my findings as below https://stackoverflow.com/a/59597360/3286489, let me know if my findings is incorrect? – Elye Jan 05 '20 at 05:47
  • Well, what makes you think there is any case where backticks are "required" (that can't be achieved single or double quotes)? – Bergi Jan 05 '20 at 09:55

1 Answers1

4

What I found is, the following can't use backtick

  1. Object declaration
                const headers2 = {
                    `Accept`: `application/json`,
                    `Content-Type`: `application/json`
                };

This will error Uncaught SyntaxError: Unexpected template string

  1. Importing module
import React from `react`;

This will error stating Parsing error: Unexpected token

Not sure if my findings are legit or there are more cases. Feel free to share.

Updated 3. Using of use strict

    `use strict`;

The above is not functioning without any warning.

Elye
  • 53,639
  • 54
  • 212
  • 474
  • I suppose template strings may be less performant compared to string literals, and as you noticed, can't be used in some cases. – KooiInc Jan 05 '20 at 05:52
  • Thanks @KooiInc. As mentioned in https://medium.com/javascript-in-plain-english/are-backticks-slower-than-other-strings-in-javascript-ce4abf9b9fa, performance differences is negligible. – Elye Jan 05 '20 at 05:53
  • Thanks for the link! So, as long as there's nothing to interpolate, backticks are fine. In that case you can use them for properties like this: `{[\`someKey\`]: \`someValue\`}` – KooiInc Jan 05 '20 at 07:29
  • Thanks @KooiInc. I also found a supporting gist stating my findings https://gist.github.com/getify/105df0a0c17892243a37c4fced1d3a8b – Elye Jan 05 '20 at 08:47