Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
5 min readView as Markdown
Template Literals in JavaScript
M

Full-stack developer with a good foundation in frontend, now specializing in backend development. Passionate about building efficient, scalable systems and continuously sharpening my problem-solving skills. Always learning, always evolving.

Thesis: Template literals are not just syntactic sugar over strings they fundamentally change how JavaScript handles string composition by introducing interpolation, multiline support, and expression evaluation inline. This reduces cognitive overhead and eliminates entire classes of bugs caused by manual concatenation.


The real problem: string concatenation doesn’t scale

Traditional string construction with + works fine until it doesn’t.

const name = "Mohammad";
const age = 22;

const message = "Hello, my name is " + name + " and I am " + age + " years old.";

Issues start appearing as complexity grows:

1. Readability degrades fast

const html =
  "<div class='user'>" +
    "<h1>" + name + "</h1>" +
    "<p>Age: " + age + "</p>" +
  "</div>";

You’re mentally parsing structure through string fragments—not the actual output.

2. Easy to introduce bugs

  • Missing +

  • Incorrect spacing

  • Wrong quote nesting

const msg = "Hello " + name + "you are " + age; // missing space

3. No natural multiline support

const text = "Line 1\n" +
             "Line 2\n" +
             "Line 3";

This is mechanical, not expressive.


Template literal syntax

Template literals use backticks (`), not quotes.

const message = `Hello, world`;

That’s the entry point. The real value comes from what you can do inside them.


Embedding variables (string interpolation)

Instead of concatenation, you embed expressions using ${}.

const name = "Mohammad";
const age = 22;

const message = `Hello, my name is \({name} and I am \){age} years old.`;

What actually happens internally

  • ${...} is evaluated as a JavaScript expression

  • Result is converted to string (ToString operation)

  • Inserted into the final string

You’re not limited to variables:

const a = 5;
const b = 10;

const result = `Sum is ${a + b}`; // Sum is 15

Even function calls:

function greet(name) {
  return `Hi ${name}`;
}

const msg = `Message: ${greet("Mohammad")}`;

Multiline strings (no hacks)

Template literals preserve line breaks exactly as written.

const text = `Line 1
Line 2
Line 3`;

No \n, no concatenation.

Why this matters in real systems

When generating:

  • HTML

  • SQL queries (carefully)

  • Emails

  • Logs

You want structure to look like structure.

const html = `
  <div class="user">
    <h1>${name}</h1>
    <p>Age: ${age}</p>
  </div>
`;

This mirrors actual DOM structure. Much easier to reason about.


Before vs After (real comparison)

Old way

const user = { name: "Mohammad", age: 22 };

const msg = "User: " + user.name + "\n" +
            "Age: " + user.age;

Template literal

const msg = `User: ${user.name}
Age: ${user.age}`;

Fewer moving parts → fewer bugs.


Use cases in production code

1. Dynamic HTML (server-side or templating)

function renderUser(user) {
  return `
    <div class="card">
      <h2>${user.name}</h2>
      <p>${user.email}</p>
    </div>
  `;
}

2. Logging with context

console.log(`User \({userId} failed login at \){new Date().toISOString()}`);

Readable logs matter during debugging.


3. SQL query construction (with caution)

const query = `SELECT * FROM users WHERE id = ${userId}`;

This is dangerous if userId is user input → SQL injection.

Correct approach:

  • Use parameterized queries

  • Never trust template literals for escaping


4. URL building

const url = `/api/users/\({userId}/posts/\){postId}`;

Cleaner than:

"/api/users/" + userId + "/posts/" + postId

5. Tagged templates (advanced but important)

Template literals can be processed before final string creation.

function tag(strings, ...values) {
  return strings[0] + values[0].toUpperCase();
}

const result = tag`hello ${"world"}`; // "hello WORLD"

Internally:

  • strings → array of literal parts

  • values → evaluated expressions

Used in:

  • CSS-in-JS (styled-components)

  • GraphQL clients

  • Sanitization libraries


Trade-offs and limitations

1. Not inherently safer

Template literals don’t escape anything automatically.

const unsafe = `<div>${userInput}</div>`;

If userInput contains <script>, you’ve created an XSS vector.


2. Performance (minor but real in tight loops)

In hot paths:

  • Repeated template literal creation can allocate new strings

  • Usually negligible unless in large loops


3. Indentation issues

Multiline strings preserve whitespace:

const text = `
    Hello
`;

Includes leading spaces. This can break:

  • HTML rendering

  • String comparisons

Solution:

  • Trim manually

  • Or avoid unnecessary indentation


Common mistakes

❌ Forgetting backticks

const msg = "Hello ${name}"; // wrong

❌ Misplacing ${}

const msg = `Hello $name`; // wrong

❌ Using template literals where simple strings are enough

const msg = `Hello`; // unnecessary

Don’t overuse them—use when interpolation or multiline adds value.


When not to use template literals

  • Static strings (no interpolation)

  • Performance-critical inner loops (micro-optimization cases)

  • Security-sensitive string building without proper sanitization


Mental model to keep

Think of template literals as:

“inline evaluated string builders with structure awareness”

They reduce:

  • manual joining

  • mental parsing

  • formatting bugs

And that’s why they’re standard in modern JavaScript codebases.