Template strings

Template strings are very simple, but they are an extremely useful addition to the JavaScript syntax. They serve three main purposes:

  • Writing multiline strings
  • String interpolation
  • Tagged template strings

Before template strings, it was quite verbose to write multiline strings. You needed to concatenate pieces of strings and append a new-line character yourself to the line endings:

const header = '<header>\n' +   '  <h1>' + title + '</h1>\n' +   '</header>'; 

Using template strings, we can simplify this example a lot. We can write multiline strings, and we can also use the string interpolation functionality for our title variable that we used to concatenate earlier:

const header = `   <header>     <h1>${title}</h1>  </header> ...

Get Mastering Angular Components now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.