Ticker

6/recent/ticker-posts

🧵 Advanced Template Literals in JavaScript – Not Just Backticks Anymore

🧵 Advanced Template Literals in JavaScript – Not Just Backticks Anymore

Most devs use template literals like this:

const name = "John";
console.log(`Hello ${name}`);

Cool… but that’s barely scratching the surface.

👉 Template literals can do way more than string interpolation.

In real apps, they help with:

  • cleaner multi-line strings
  • dynamic content generation
  • even building mini “DSL-like” patterns (yeah, seriously)

Let’s go a bit deeper — the stuff you don’t usually see in basic tutorials.

⚡ Multi-line Strings (Without the Mess)

Before template literals… this was pain:

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

Now:

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

👉 Much cleaner. No escaping. No concatenation.

🔎 Expression Power (Not Just Variables)

You’re not limited to variables inside ${}.

const a = 10;
const b = 20;

console.log(`Sum is ${a + b}`);

Even functions:

const format = (name) => name.toUpperCase();

console.log(`User: ${format("john")}`);

👉 Anything that returns a value works here.

🔥 Real Use Case: Dynamic HTML (Careful Though 👀)

const user = { name: "John", age: 25 };

const html = `
  <div>
    <h2>${user.name}</h2>
    <p>${user.age}</p>
  </div>
`;

Super readable.

But…

👉 Don’t blindly inject user input → XSS risk

🧠 Tagged Template Literals (This Is the Advanced Part)

This is where things get interesting.

You can intercept template literals with a function.

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i] ? `<strong>${values[i]}</strong>` : "";
    return result + str + value;
  }, "");
}

const name = "John";

const output = highlight`Hello ${name}`;

console.log(output);

👉 Output:

Hello <strong>John</strong>

What’s happening?

  • strings → static parts
  • values → dynamic values

You control how everything is combined.

🔥 Real Use Case: Safe HTML Escaping

function escapeHTML(strings, ...values) {
  const escape = (str) =>
    str.replace(/</g, "&lt;").replace(/>/g, "&gt;");

  return strings.reduce((result, str, i) => {
    const value = values[i] ? escape(values[i]) : "";
    return result + str + value;
  }, "");
}

const userInput = "<script>alert('hack')</script>";

const safe = escapeHTML`User input: ${userInput}`;

console.log(safe);

👉 Prevents XSS-style injection.

This is how some templating systems work internally.

💡 Real Developer Insight

Most devs stop at:

👉 ${variable}

But in larger apps:

  • Tagged templates can standardize formatting
  • You can build reusable string processors
  • Libraries (like styled-components) rely heavily on this

Also:

👉 Template literals improve readability a lot… until they don’t.

If you nest too much logic inside ${}, it becomes unreadable.

⚠️ Common Developer Mistakes

1️⃣ Overloading expressions

`${user.age > 18 ? calculateSomethingComplex() : fallback()}`

👉 Hard to read. Move logic outside.

2️⃣ Ignoring security

Injecting raw user data into HTML = 🚨

3️⃣ Using template literals for everything

Sometimes simple strings are clearer.

4️⃣ Not understanding tagged templates

They look weird at first, so people avoid them completely.

🚀 Best Practice Summary

✅ Use template literals for cleaner string interpolation
✅ Keep expressions inside ${} simple and readable
✅ Use tagged templates for advanced formatting or sanitization
✅ Avoid injecting raw user input directly into HTML
✅ Prefer readability over clever one-liners

Reactions

Post a Comment

0 Comments