Skip to main content

Command Palette

Search for a command to run...

JavaScript Template Literals: Goodbye String Concatenation

Updated
2 min readView as Markdown
JavaScript Template Literals: Goodbye String Concatenation

Template literals transform how we build strings in JavaScript making code cleaner, more readable, and far less error-prone. Here's everything you need to know.

1 . The problem with traditional string concatenation

Before ES6 building string meant chaining values together with + operators. The result were verbose, fragile, and nearly impossible to scan at a glance.

Common pitfalls of the old approach: missed spaces between values, forgotten quotes, unreadable nested quotes, and multi-line string requiring \n escape sequences throghout.


2. Template literal syntax

The entire syntax change is just two characters: swap your quotes (' or ") for backticks (`). Everything else follows naturally.

`.....` → Backtick delimiters - replace quotes

`${}` → Interpolation slot - any JS expression inside

newlines → Real line breaks, no \n needed

\` → Escape a literal backtick if needed

// Basic syntax
const greeting = `Hello, World!`;

// Expression interpolation
const price = 9.99;
const tax = 0.18;
const total = `Total: $${price * (1 + tax)).toFixed(2)}
// "Total: $11.79

3. Multi-line string

Template literals preserve preserve whitespace and newlines exactly as you type them. No + operator, no \n escapes, no string concatenation across lines.

// Before painful
const query = "Select id, name\n" +
              "From user\n" +
              "Where active = true";

// After: natural
const query = `
  Select id, name 
  From users
  Where active = ${isActive}
`;

Key takeaways

Readability wins. Template literals collapse three painful problems — concatenation noise, multi-line workarounds, and expression embedding — into one clean syntax.

Expressions, not just variables. Anything inside ${ } is executed as JavaScript: function calls, ternary operators, arithmetic, method chains.

Tagged templates go further. Libraries like styled-components, graphql-tag, and sql use tagged templates to build entire DSLs inside JavaScript strings.

Use template literals everywhere you'd previously use string concatenation. Your future self — and your teammates — will thank you.