Advanced15 min read

Template Literals

Use backtick strings for string interpolation, multi-line strings, and tagged templates in JavaScript.

Template Literal Basics

Template literals use backticks (`) instead of single or double quotes. They unlock two powerful features: string interpolation and multi-line strings.

The most useful feature is string interpolation with ${expression}. Any valid JavaScript expression can go inside the ${}:

javascript
const name = 'Alice';
const age = 30;

// Old way — string concatenation
const greeting = 'Hello, ' + name + '! You are ' + age + ' years old.';

// New way — template literal
const greeting2 = `Hello, ${name}! You are ${age} years old.`;

The expression inside ${} can be anything that produces a value — variables, arithmetic, function calls, ternary operators:

javascript
console.log(`2 + 3 = ${2 + 3}`);           // '2 + 3 = 5'
console.log(`Uppercase: ${'hello'.toUpperCase()}`); // 'Uppercase: HELLO'
console.log(`Status: ${age >= 18 ? 'adult' : 'minor'}`); // 'Status: adult'

Backticks also allow you to freely use single and double quotes inside the string without escaping:

javascript
const quote = `She said "it's fine" and walked away.`;

This makes template literals the preferred string syntax in modern JavaScript.

Multi-line Strings

Template literals preserve newlines and whitespace exactly as written. This eliminates the need for \n escape characters or awkward string concatenation:

javascript
// Old way
const old = 'Line 1\n' +
  'Line 2\n' +
  'Line 3';

// New way — just press Enter
const poem = `Roses are red,
Violets are blue,
Template literals
Are awesome too.`;

This is especially useful for building HTML templates in JavaScript:

javascript
const card = `
  <div class="card">
    <h2>${title}</h2>
    <p>${description}</p>
  </div>
`;

One thing to watch out for: all whitespace is preserved, including indentation. If you indent the template literal to match your code style, that indentation becomes part of the string:

javascript
function getHTML() {
  return `
    <p>Hello</p>
  `;
  // The string starts with a newline and 4 spaces!
}

For most DOM uses (like innerHTML), the extra whitespace is harmless because HTML collapses whitespace anyway. But keep it in mind when whitespace matters (like <pre> tags or comparing strings).

Tagged Templates

Tagged templates are an advanced feature where you place a function name before the template literal. The function receives the string parts and interpolated values as separate arguments:

javascript
function highlight(strings, ...values) {
  let result = '';
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      result += `<strong>${values[i]}</strong>`;
    }
  });
  return result;
}

const name = 'Alice';
const role = 'developer';
const html = highlight`Welcome ${name}, you are a ${role}!`;
// 'Welcome <strong>Alice</strong>, you are a <strong>developer</strong>!'

The tag function receives:

  • strings — an array of the literal string pieces: ['Welcome ', ', you are a ', '!']
  • ...values — the evaluated expressions: ['Alice', 'developer']

You will encounter tagged templates in popular libraries:

  • styled-components: styled.div`color: red;`
  • GraphQL: gql`query { users { name } }`
  • Lit HTML: html`<p>${text}</p>`

You do not need to write your own tagged templates often, but understanding the concept helps when reading library code.

Template Literals in Action

html
<div id="output"></div>

<script>
  const name = 'Alice';
  const score = 95;
  const passed = true;

  // String interpolation
  const message = `${name} scored ${score}/100`;

  // Expression inside ${}
  const status = `Result: ${passed ? 'PASSED' : 'FAILED'}`;

  // Multi-line HTML template
  const card = `
    <div style="border:1px solid #555; padding:12px; border-radius:8px;">
      <h3>${name}</h3>
      <p>${message}</p>
      <p><em>${status}</em></p>
    </div>
  `;

  document.getElementById('output').innerHTML = card;
</script>

What is the output of `Hello ${2 + 3} world`?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.