What are template literals?

Template literals are strings written with backticks that support embedded expressions (${...}), real multi-line text and, through tagged templates, custom processing of the string parts and values.

Interpolation

Any expression can go inside ${ }: variables, calls, ternaries, arithmetic. The result is converted to a string.

Multi-line strings

Line breaks inside backticks are kept as-is, no \n needed. Indentation is kept too, which is something to watch for.

Tagged templates

A function placed in front of a template (tag`...`) receives the string pieces and the values separately and can return anything. This powers:

  • Safe HTML or SQL builders that escape values.
  • Styling libraries (styled.div`...`).
  • GraphQL queries (gql`...`).
  • String.raw, which keeps backslashes literal: String.raw`C:\new`.

Pitfalls

  • Building HTML with plain interpolation of user input is an XSS risk. Escape the values or use a tag that does.
  • Building SQL with interpolation is an injection risk. Use parameterised queries.
  • ${obj} prints [object Object]; use JSON.stringify for debugging.

Code example

js
1const user = { name: "Ada", items: 3, total: 42.5 };
2
3console.log(`Hi ${user.name}, you have ${user.items} item${user.items === 1 ? "" : "s"}`);
4console.log(`Total with tax: ${(user.total * 1.2).toFixed(2)}`);
5
6const receipt = `Receipt
7 Name: ${user.name}
8 Total: ${user.total}`;
9console.log(receipt); // keeps the line breaks and indentation
10
11// Tagged template that escapes values for HTML
12const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
13function html(strings, ...values) {
14 return strings.reduce((out, str, i) => out + str + (i < values.length ? escape(values[i]) : ""), "");
15}
16const comment = '<img src=x onerror="alert(1)">';
17console.log(html`<p>${comment}</p>`); // <p>&#60;img src=x onerror=&#34;alert(1)&#34;&#62;</p>
18
19console.log(String.raw`C:\new\folder`); // C:\new\folder (backslashes kept)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app