Hiprup

What are template literals in JavaScript?

Template literals are strings written with backticks that support interpolation and multi-line text.

  • Interpolation — embed variables and expressions directly inside the string.

  • Multi-line — line breaks are preserved without escape characters.

  • Tagged templates — a function can process the string and its values for custom formatting.

Benefit: they replace clumsy string concatenation with readable, expressive strings.

const name = 'John';
const age = 30;

// Interpolation
console.log(`Hello, ${name}! You are ${age} years old.`);
console.log(`Next year: ${age + 1}`);
console.log(`Status: ${age >= 18 ? 'adult' : 'minor'}`);

// Multi-line
const html = `
  <div class="card">
    <h1>${name}</h1>
    <p>Age: ${age}</p>
  </div>
`;

// Tagged templates
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
  }, '');
}

const result = highlight`Hello, ${name}! You are ${age}.`;
// 'Hello, <mark>John</mark>! You are <mark>30</mark>.'

${expression} embeds any JS expression. Multi-line strings preserve actual newlines. Tagged templates pass the template parts to a function: strings gets the literal parts, values gets the interpolated values.

The highlight tag wraps values in <mark> tags. Tagged templates enable: HTML escaping, internationalization, CSS-in-JS, and GraphQL queries.

Show interpolation (${expression}), multi-line strings, and tagged templates. Tagged templates are the advanced feature most candidates miss — they power styled-components (CSS-in-JS) and GraphQL queries.

Know that any expression works inside ${}.

What are template literals in JavaScript? | Hiprup