JavaScriptEasy
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]; useJSON.stringifyfor debugging.
Code example
js
1const user = { name: "Ada", items: 3, total: 42.5 };23console.log(`Hi ${user.name}, you have ${user.items} item${user.items === 1 ? "" : "s"}`);4console.log(`Total with tax: ${(user.total * 1.2).toFixed(2)}`);56const receipt = `Receipt7 Name: ${user.name}8 Total: ${user.total}`;9console.log(receipt); // keeps the line breaks and indentation1011// Tagged template that escapes values for HTML12const 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><img src=x onerror="alert(1)"></p>1819console.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.