Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Published
3 min read

Modern JavaScript has evolved significantly, and one feature that drastically improves how we work with strings is Template Literals.

If you've ever struggled with messy string concatenation, this is going to feel like a superpower.


🔴 Problems with Traditional String Concatenation

Before ES6, we used the + operator to build strings:

const name = "Sayantan";
const age = 21;

const message = "My name is " + name + " and I am " + age + " years old.";
console.log(message);

Issues with this approach:

  • ❌ Hard to read as strings grow longer

  • ❌ Too many + operators

  • ❌ Easy to make mistakes (missing spaces, quotes, etc.)

  • ❌ Not suitable for multi-line strings

Example of messy code:

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

This quickly becomes unreadable.


🟢 What Are Template Literals?

Template literals are a modern way to work with strings using backticks ( ) instead of quotes.

const message = `This is a template literal`;

🧩 Template Literal Syntax

const variable = `string text`;

Key features:

  • Uses backticks `

  • Supports interpolation

  • Supports multi-line strings


🔗 Embedding Variables (Interpolation)

Instead of concatenation, we use ${}:

const name = "Sayantan";
const age = 21;

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

console.log(message);

Why this is better:

  • ✅ Cleaner syntax

  • ✅ More readable

  • ✅ Less error-prone


📏 Multi-line Strings Made Easy

With normal strings:

const text = "This is line 1\nThis is line 2";

With template literals:

const text = `This is line 1
This is line 2`;

console.log(text);

No \n, no hacks — just write naturally.


⚔️ Comparison: Old vs Modern

❌ Old Way (Concatenation)

const name = "Sayantan";
const greeting = "Hello " + name + ", welcome!";

✅ New Way (Template Literals)

const name = "Sayantan";
const greeting = `Hello ${name}, welcome!`;

👉 The second version is shorter, cleaner, and more readable.


💡 Use Cases in Modern JavaScript

1. Dynamic Strings

const price = 99;
console.log(`The price is ₹${price}`);

2. HTML Templates (Very Common in Frontend)

const user = "Sayantan";

const html = `
  <div>
    <h1>${user}</h1>
    <p>Welcome to the website</p>
  </div>
`;

3. Logging & Debugging

const value = 42;
console.log(`The value is: ${value}`);

4. Function Expressions Inside Strings

const a = 5;
const b = 10;

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

🧠 Why Template Literals Matter

Template literals are not just syntactic sugar—they improve:

  • 📖 Readability

  • Developer productivity

  • 🧩 Maintainability of code

  • 🧼 Cleaner UI rendering (especially in React/JS apps)