JavaScript Template Literals

Template literals (introduced in ES6) provide an easy way to create strings with embedded expressions, multi-line content, and advanced formatting using backtick (`) characters instead of quotes.

Backtick Syntax

Template literals use backticks (` `) instead of single or double quotes. They allow you to create strings that look cleaner and are easier to read.

Basic Template Literal
let greeting = `Hello, World!`;
console.log(greeting);

// Quotes inside backticks need no escaping
let phrase = `He said "Hello" and she said 'Hi'`;
console.log(phrase);

Expression Interpolation (${...})

The real power of template literals is string interpolation. Use ${expression} to embed any JavaScript expression directly inside the string. The expression is evaluated and its result is converted to a string.

Variable Interpolation
let firstName = "John";
let lastName = "Doe";
let fullName = `My name is ${firstName} ${lastName}`;
console.log(fullName);

let price = 19.99;
let tax = 0.08;
let total = `Total: $${(price * (1 + tax)).toFixed(2)}`;
console.log(total);
Expressions Inside ${}
let a = 10;
let b = 20;
console.log(`Sum: ${a + b}`);
console.log(`Is a bigger? ${a > b}`);
console.log(`Uppercase: ${"hello".toUpperCase()}`);
console.log(`Ternary: ${a > 5 ? "big" : "small"}`);

Multi-Line Strings

With template literals, you can create multi-line strings without using escape characters like \n. The line breaks in your code are preserved in the output.

Multi-Line Template Literal
let poem = `Roses are red,
Violets are blue,
Template literals,
Are awesome too!`;
console.log(poem);

// Compare with old approach:
let oldWay = "Line 1\n" +
             "Line 2\n" +
             "Line 3";
console.log(oldWay);

Tagged Templates

Tagged templates let you parse template literals with a function. The tag function receives the string parts and expression values as separate arguments, giving you full control over how the template is processed.

Tagged Template Function
function highlight(strings, ...values) {
  let result = "";
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      result += `[${values[i]}]`;
    }
  });
  return result;
}

let name = "Alice";
let age = 30;
let msg = highlight`Name: ${name}, Age: ${age}`;
console.log(msg);
Practical Tagged Template: HTML Escaping
function safeHTML(strings, ...values) {
  let result = "";
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      result += String(values[i])
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;");
    }
  });
  return result;
}

let userInput = "<script>alert('xss')</script>";
let html = safeHTML`<p>User said: ${userInput}</p>`;
console.log(html);

Nesting Templates

Template literals can be nested inside the ${} expressions of other template literals. This is useful for building complex strings conditionally.

Nested Template Literals
let isLoggedIn = true;
let user = "Alice";

let message = `Welcome ${isLoggedIn ? `back, ${user}` : `guest`}!`;
console.log(message);

let items = ["apple", "banana", "cherry"];
let list = `Items: ${items.map(item => `"${item}"`).join(", ")}`;
console.log(list);
FeatureRegular StringsTemplate Literals
Delimiter' or "` (backtick)
InterpolationNot supported${expression}
Multi-lineRequires \nNatural line breaks
TaggedNot supportedtag`string`
Expression embeddingConcatenation onlyAny JS expression
📝 Note: Template literals are not just syntactic sugar. Tagged templates enable powerful patterns like styled-components in React, GraphQL query definitions (gql`...`), and internationalization (i18n) libraries.
Exercise:
What is the correct syntax to embed a variable 'name' in a template literal?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.