5

I've been into the discussion of single or double qoutes for string literals in Javascript (JSON aside), and it seems that the choosing of one or another is purely arbitrary, with two clarifications:

  • Use the same convention over all your code (no var a="a", b='b').
  • You can be flexible to accommodate literals that would otherwise require to escape a lot of characters, hurting readability (no its='it\'s' nor normal="the \"normal\" thing").

But we have now another qouting character, the backtick that is used in template literals, that by itself is much less frequently used in normal text or code than the other two, and hence requires less escaping:

youre = `You're so "normal"!`

At most, one would need to espace the dollar sign in the cases where that would make an unwanted embedded expression.

I try to think of reasons to avoid using the backtick as a coding standard, replacing the other two.

  • Is it going to hurt performance? I guess not really (I tried to measure but got inconclusive results). If performance depends only in the number of characters to escape, you could see an improvement from the edge cases like youre or literals with newlines.
  • Slower typing? It will depend on your keyboard. In mine (Spanish), both double and single quotes are in the numbers row and are harder to reach, and the double requires me to press Shift, while the backtick is just a key away from my finger but requires to press Space, so it's hard to say it will be for me.
  • Browser compatibility? Probably. But time solves it, and there are cases where it is not relevant, like anything intended to run in Node.js.

Are there other reasons that may discourage (or encourage) one to set the backtick as the qoute for string literals in the coding standard of your projects?

dmcontador
  • 660
  • 1
  • 8
  • 18

1 Answers1

1

Using Backticks for Strings allows to create Template Strings.

const create = word => `Hello ${word}`

console.log(create("World")); // Hello World

So this is a cleaner way to create/interpolate Strings. Since the transpiler/interpreter will turn that back into something like: "Hello" + word the impact on Performance should depend on the number of Strings to combine and the overall length of the String.

No matter which »type« of String you chose if you need the quoting characters in it, you need to escape them:

console.log(```) // SyntaxError
console.log(`\``) // `

So all in all, template Strings are great for templates, so use them for it if you like, but it wont make any difference, when it comes to escaping, plus, you have to escape $ signs, too.

philipp
  • 15,947
  • 15
  • 61
  • 106