The Codex / JavaScript / Template Literals

Template Literals

Backtick strings with embedded expressions, multiline text, and tagged templates — JavaScript's modern string syntax.

What it is, in plain English: A template literal is a string delimited by backticks (`) instead of quotes. It supports two things regular strings don't: embedded expressions with ${...} that are evaluated and inserted inline, and multiline text without escape characters. A tagged template is a function call where the function receives the string parts and expression values separately — used to build SQL queries, HTML sanitisers, CSS-in-JS, and more.

Backtick strings — the modern way to build strings

Before ES2015, building strings with variables required awkward concatenation with +. Template literals replace that with a cleaner syntax using backticks and ${}.

Basic interpolation

const city  = "Mumbai";
const temp  = 34;
const feels = "humid";

// Old way — hard to read:
const old = "It's " + temp + "°C in " + city + " and feels " + feels + ".";

// Template literal — much cleaner:
const msg = `It's ${temp}°C in ${city} and feels ${feels}.`;
console.log(msg);
// "It's 34°C in Mumbai and feels humid."

Any expression goes inside ${}

const a = 10, b = 3;

console.log(`${a} + ${b} = ${a + b}`);           // "10 + 3 = 13"
console.log(`${a} × ${b} = ${a * b}`);           // "10 × 3 = 30"
console.log(`Max: ${Math.max(a, b)}`);            // "Max: 10"
console.log(`${a > b ? "a wins" : "b wins"}`);   // "a wins"

// Function calls work too:
const name = "alice";
console.log(`Hello, ${name.toUpperCase()}!`);     // "Hello, ALICE!"
console.log(`Name has ${name.length} letters`);   // "Name has 5 letters"

Multiline strings — no \n needed

// Old way — escape characters:
const old = "Line 1
Line 2
Line 3";

// Template literal — just press Enter:
const poem = `
  Roses are red,
  Violets are blue,
  JavaScript is great,
  And template literals too.
`;
console.log(poem);

Building HTML and URLs

// Building HTML strings:
const user = { name: "Bob", score: 87 };
const card = `
  <div class="user-card">
    <h2>${user.name}</h2>
    <p>Score: <strong>${user.score}</strong></p>
  </div>
`;

// Building URLs:
const baseUrl = "https://api.example.com";
const userId  = 42;
const url = `${baseUrl}/users/${userId}/profile`;
console.log(url);  // "https://api.example.com/users/42/profile"

// Nesting template literals (loop inside template):
const fruits = ["mango", "guava", "papaya"];
const list = `
  <ul>
    ${fruits.map(f => `<li>${f}</li>`).join("
    ")}
  </ul>
`;
Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.