Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
•4 min read•View as Markdown

If you wrote JavaScript before 2015, you likely have some lingering trauma from trying to build complex strings.

String concatenation—the act of joining multiple strings and variables together—used to be an incredibly tedious process. It involved a chaotic symphony of quotation marks, plus signs, and inevitably, a frustrating hunt for a missing space that was messing up your entire output.

Thankfully, ES6 introduced Template Literals. This syntax didn't just add a new feature; it fundamentally fixed how we write and read text in JavaScript.

Let’s look at the old problems we used to face, and how template literals clean up our code.

The Problem: The "Plus Sign" Fatigue

Before template literals, if you wanted to combine variables with text, you had to use the + operator.

Imagine you are building a dashboard for a trading platform and need to display a simple transaction message.

// The Old Way: String Concatenation
var username = "Alex";
var ticker = "AAPL";
var shares = 15;
var price = 150.50;

var message = "Alert: " + username + " just bought " + shares + " shares of " + ticker + " at $" + price + " per share.";

console.log(message);

Look at how messy that message variable is. You have to constantly open and close quotes, remember to add manual spaces inside those quotes, and string everything together with plus signs. It is hard to write, harder to read, and incredibly prone to typos.

The Solution: Enter the Backtick

Template literals replace the standard single '' or double "" quotes with the backtick ` (usually located directly above the Tab key on your keyboard).

By wrapping your string in backticks, you unlock the ability to inject variables and expressions directly into the text.

1. Embedding Variables (String Interpolation)

With template literals, you no longer need the plus sign to glue things together. Instead, you use a syntax called interpolation: ${variableName}.

Let’s rewrite our trading alert from above:

// The New Way: Template Literals
const username = "Alex";
const ticker = "AAPL";
const shares = 15;
const price = 150.50;

const message = `Alert: \({username} just bought \){shares} shares of ${ticker} at $${price} per share.`;

console.log(message);

The Readability Upgrade: Notice how the string flows exactly like a normal human sentence. You don't have to stop and start the string; you just drop the variables into their placeholders (${}). The visual noise of the + operator is completely gone.

Pro-tip: You aren't limited to just variables! You can put any valid JavaScript expression inside the ${}—like math calculations or function calls: Total cost: $${shares * price}.

2. Conquering Multi-Line Strings

Embedding variables is great, but template literals might shine the brightest when dealing with multiple lines of text.

Historically, if you wanted a string to span multiple lines (like when generating HTML snippets or writing formatted terminal logs), you had to use the awkward \n newline character and concatenate every single line.

// The Old Way: Multi-line HTML
var title = "Portfolio Overview";
var htmlString = "<div class='card'>\n" +
                 "  <h2>" + title + "</h2>\n" +
                 "  <p>Loading your assets...</p>\n" +
                 "</div>";

With template literals, the backticks respect your keyboard's "Enter" key. If you drop to a new line in your code, it drops to a new line in the string.

// The New Way: Multi-line Template Literals
const title = "Portfolio Overview";

const htmlString = `
  <div class='card'>
    <h2>${title}</h2>
    <p>Loading your assets...</p>
  </div>
`;

This makes creating dynamic UI components, SQL queries, or formatted emails infinitely cleaner.

Use Cases in Modern JavaScript

Template literals are everywhere in modern development. You will find yourself using them constantly for:

  • API URLs: Dynamic routing becomes a breeze (e.g., const endpoint = \https://www.google.com/search?q=https://api.example.com/users/\){userId}/data`;`).

  • React and Frontend Frameworks: Crafting dynamic class names (e.g., className={\btn ${isActive ? 'btn-active' : ''}`}`).

  • Logging and Error Handling: Creating detailed, readable error messages for backend microservices or terminal outputs.