← Back to Chapters

JavaScript Template Literals

? JavaScript Template Literals

⚡ Quick Overview

Template literals (introduced in ES6) are a modern way to create strings in JavaScript using backticks (`) instead of quotes. They make it easy to:

  • Insert variables directly into strings (string interpolation).
  • Create multi-line strings without \n.
  • Embed expressions and simple calculations in strings.
  • Build readable, formatted output for the browser or console.

They look like this: `Hello, ${name}!`

? Key Concepts

  • Backticks instead of single (') or double (") quotes.
  • Interpolation using ${ ... } to insert variables/expressions.
  • Multi-line strings without concatenation or \n.
  • Expression support, including function calls and simple math.
  • Tagged templates (advanced) for custom string processing.

? Syntax & Theory

Basic template literal:

  • Starts and ends with backticks: `
  • Can contain plain text, variables, and expressions.

Interpolation syntax:

  • Wrap the expression inside ${ ... } inside the template literal.
  • Anything valid in JavaScript expressions can go inside ${ }.

Multi-line strings:

  • Just press Enter inside the backticks; the newlines are preserved.
? View Basic Syntax Example
// Using normal string concatenation
const firstName = "Alex";
const age = 21;
const oldWay = "Name: " + firstName + ", Age: " + age + " years.";
console.log(oldWay);

// Using template literals
const newWay = `Name: ${firstName}, Age: ${age} years.`;
console.log(newWay);

// Multi-line template literal
const multiLine = `Student:
- Name: ${firstName}
- Age: ${age}
- Status: Active`;
console.log(multiLine);

? Code Examples

? Interpolating Expressions

You can put full expressions inside ${ }, not just simple variables.

? View Expression Example
const a = 10;
const b = 5;
const result = `Sum: ${a + b}, Product: ${a * b}`;
console.log(result); // Sum: 15, Product: 50

// Calling functions inside ${}
function fullName(first, last) {
  return `${first} ${last}`;
}

const greeting = `Hello, ${fullName("Alex", "Johnson")}!`;
console.log(greeting);

? Multi-line Strings

Without template literals, you had to concatenate or use \n. With backticks, you simply write multiple lines.

? View Multi-line Example
// Before (hard to read)
const messageOld = "Shopping List:\n" +
"- Milk\n" +
"- Bread\n" +
"- Eggs";

// With template literal (clean)
const messageNew = `Shopping List:
- Milk
- Bread
- Eggs`;

console.log(messageNew);

?️ Tagged Template (Preview)

Tagged templates let you call a function on a template literal to customize how it is processed. This is an advanced use case.

? View Tagged Template Example
function highlight(strings, ...values) {
  console.log(strings); // Array of string parts
  console.log(values);  // Array of interpolated values
  return strings.reduce((finalStr, currentStr, index) => {
    const value = values[index] !== undefined ? `*${values[index]}*` : "";
    return finalStr + currentStr + value;
  }, "");
}

const lang = "JavaScript";
const level = "beginner";
const sentence = highlight`You are learning ${lang} at ${level} level.`;

console.log(sentence);
// Output: You are learning *JavaScript* at *beginner* level.

? Live Output & Explanation

Below is a small interactive example. Type your name and favorite language, and see how a template literal creates a dynamic message in real time.

? Interactive Demo

 

The script uses a template literal to combine the values from the two text fields into a single readable sentence.

? View Demo JavaScript Code
const nameInput = document.getElementById("nameInput");
const langInput = document.getElementById("langInput");
const resultPara = document.getElementById("demoResult");
const buildButton = document.getElementById("buildMessageBtn");

buildButton.addEventListener("click", () => {
  const name = nameInput.value.trim() || "Student";
  const language = langInput.value.trim() || "JavaScript";

  const message = `Hello, ${name}! ?
You picked ${language} as your favorite language. Keep coding!`;

  resultPara.textContent = message;
});

? Common Use Cases

  • Building readable console logs for debugging.
  • Creating HTML snippets dynamically in JavaScript.
  • Generating formatted emails, messages, or notifications.
  • Logging values and labels together clearly (e.g., `x = ${x}, y = ${y}`).
  • Simplifying string-heavy code in Node.js and front-end apps.

? Helpful Tips

  • Use template literals for any string that contains variables or expressions.
  • Prefer template literals over string concatenation for clarity and readability.
  • Keep complex logic out of ${ }; move it into functions when needed.
  • Remember that backticks are different from single/double quotes.
  • Use multi-line template literals for readable output (logs, HTML snippets, messages).

? Practice Tasks

  1. Create a template literal that prints your name, course, and college in three lines using a single variable.
  2. Write a function formatMarkSheet(name, subject, marks) that returns a multi-line string using template literals to display a neat mark sheet.
  3. Convert an existing program that uses string concatenation to template literals and compare the readability.
  4. Create a tagged template that wraps all interpolated values in [ ] and test it with at least two values.