Code Reference

Template Literals Basics

JavaScript · Reference cheat sheet

Template Literals Basics

JavaScript · Reference cheat sheet


📋 Overview

Template literals are strings wrapped in backticks (`). They support interpolation with $\{...\} and multi-line text without awkward + concatenation.

🔧 Core concepts

FeatureSyntaxPurpose
Template`text`String with superpowers
Interpolation`$\{expr\}`Embed any expression
Multi-lineNewlines inside backticksReadable paragraphs
NestedTemplates inside $\{\}Advanced formatting
Tagged templatestag\...``Advanced (libraries, i18n)

Prefer templates over + when building messages from variables.

💡 Examples

Interpolation:

const name = "Ada";
const score = 95;
console.log(`Hello, ${name}! Score: ${score}`);

Expressions inside ${}:

const a = 3;
const b = 4;
console.log(`${a} + ${b} = ${a + b}`);
console.log(`Upper: ${"hi".toUpperCase()}`);

Multi-line:

const html = `
<section>
  <h1>Title</h1>
  <p>Hello</p>
</section>
`.trim();
console.log(html);

Compared to concatenation:

const user = "Sam";
const oldWay = "Hi " + user + "!";
const newWay = `Hi ${user}!`;
console.log(oldWay === newWay); // true

⚠️ Pitfalls

  • Use backticks `, not quotes — "Hello $\{name\}" does not interpolate.
  • Nested quotes are fine inside templates; escaping backticks needs ```.
  • Huge templates with logic become hard to read — extract variables first.
  • Accidental leading indentation in multi-line templates is part of the string.

On this page