Search code examples
javascriptecmascript-6string-interpolation

ES6 Feature: How are Template Strings useful?


AKA Template Literals, String Interpolation. (Wiki here.)

Why are they useful?

When should I not use them?

How are these features similar and different from using JSX with React?

How can I use String.raw() effectively as mentioned in the bottom of the wiki?


Solution

  • The string templating (or string interpolation) feature is ubiquitous in many programming languages. You should use it when you have a distinct or recurring template that you wish to fill in with the variables in current scope. It makes the template more readable than concatenation of strings or printf-style formatting.

    The difference with JSX is that JSX is intended for templating HTML, whereas string templates are for templating any kind of text, for instance, log messages or user output.

    The raw strings may be useful when you wish to operate on a string that has a lot of actual backslashes, not escaping backslashes. For instance, if you want to describe a string \n\r\u0000, then you would write it as \\n\\r\\u0000, which is not very readable. With raw strings, you can write it as String.raw('\n\r\u0000').