iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Template Literals

Template literals are backtick strings with embedded expressions. They replace string concatenation, support multi-line literals, and unlock tagged templates for safer DSLs.

The basics

JS
const name = "Ada", age = 36;

// Interpolation
`Hi, ${name}, age ${age}.`              // "Hi, Ada, age 36."

// Expressions
`Total: $${(qty * price).toFixed(2)}`

// Multi-line
`
<article>
  <h1>${name}</h1>
</article>
`

Tagged templates

A tag is a function that receives the static parts and the interpolated values separately — useful for sanitisation and DSLs.

JS
function safe(strings, ...values) {
  return strings.reduce((acc, s, i) => {
    const v = values[i - 1];
    return acc + (v === undefined ? "" : escapeHtml(v)) + s;
  });
}

const html = safe`<p>Hi ${userName}</p>`;

Practical uses

UseExample tag
HTML escapingLit's html tag
CSS-in-JSstyled-components' css tag
SQL templatingsql.js, slonik
i18nThe t tag in many libraries
Tip: When the engine sees the same template at the same site repeatedly, the array of strings is cached — that's why tagged templates are cheap to call in a loop.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Template Literals!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Interpolate `name` into a template literal.

const msg = `Hi, {name}!`;

Test yourself

Q1. Template literals are wrapped in…
Q2. A tagged template is a function that…
Q3. Template literals across multiple lines work…

Discussion

Loading…