Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Writing Cleaner, Readable and Dynamic Strings Without the Mess

Updated
•3 min read•View as Markdown

Working with strings is something we do constantly in JS. Whether it's building messages, rendering UI or handling dynamic data. But if we have ever used traditional string concatenation with + , we already know how messy it can get.

Template literals solve this problem by making string handing cleaner, more readable and easier to maintain.


Problems with Traditional String Concatenation

Before template literals, we used + to combine strings and variables.

const name = "Mith";
const age = 25;

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

Issues here:

  • Hard to read as complexity increases

  • Easy to miss spaces or quotes

  • Multi-line strings are painful

  • Debugging becomes annoying

Now imagine this with 5–6 variables — it quickly becomes unreadable.


Template Literal Syntax

Template literals use backticks (`) instead of quotes.

const message = `This is a template literal`;

This small change unlocks powerful features.


Embedding Variables in Strings

Instead of breaking the string, you can directly inject variables using ${}.

const name = "Elon";
const age = 45;

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

console.log(message);
  • Cleaner syntax

  • No need to break the string

  • Easy to understand at a glance


Multi-line Strings with template literals:

const text = `This is line one.
This is line two.
This is line three.`;

console.log(text);
  • Preserves formatting naturally

  • No escape characters needed


Use Cases in Modern JavaScript

  1. Dynamic UI Strings

    const username = "elon";
    
    const greeting = `Welcome back, ${username}!`;
    
  2. HTML Templates (Very common in Frontend)

    const user = {
      name: "Pramith",
      age: 25
    };
    
    const card = `
      <div>
        <h2>${user.name}</h2>
        <p>Age: ${user.age}</p>
      </div>
    `;
    
  3. Conditional Rendering Inside Strings

    const isLoggedIn = true;
    
    const message = `User is ${isLoggedIn ? "logged in" : "logged out"}`;
    
  4. Expression Evaluation

    const a = 10;
    const b = 20;
    
    console.log(`Sum is ${a + b}`);
    

Important Insight

Template literals are not just about syntax — they change how we think about string construction.

Instead of joining pieces, we start writing strings as they should look, and inject values where needed.

This reduces cognitive load while reading and writing code.


1 views