Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
7 min read
Template Literals in JavaScript

1) Problems with Traditional String Concatenation

Traditional string concatenation (using +) works, but it becomes problematic as your code grows. It often leads to messy, hard-to-read, and error-prone code—especially in real-world applications.

i ) Poor Readability

When multiple variables are combined, the code quickly becomes cluttered and difficult to understand.

let name = "John";
let age = 25;

let message = "Hello " + name + ", you are " + age + " years old.";

ii ) Difficult to Manage Long Strings

For longer messages, concatenation becomes messy and confusing.

let text = "This is a long message " +
           "that spans multiple lines " +
           "and becomes hard to manage.";

👉 You have to manually handle spaces and line breaks.

iii ) Error-Prone (Missing Spaces / Symbols)

It’s easy to forget spaces or add extra symbols, which leads to bugs.

let message = "Hello"+name+"welcome!"; // Missing spaces

👉 Output becomes incorrect: "HelloJohnwelcome!"

iv ) Hard to Debug

When something goes wrong, it’s difficult to spot errors in long concatenated strings.

let msg = "User: " + user.name + ", Age: " + user.age + ", City: " + user.city;

👉 One small mistake can break the entire string.

v ) No Multi-line Support

You cannot easily write multi-line strings without using special characters.

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

👉 Makes the code less clean and readable.

vi ) Hard to Include Expressions

Complex expressions make concatenation ugly and confusing.

let total = "Total: " + (price * quantity);

👉 Works, but becomes messy with more logic.

vii ) Maintenance Becomes Difficult

If you need to update or reorder text, concatenation becomes harder to manage.

👉 Especially in large applications or dynamic content.


2) Template Literal Syntax – Suggestions

Template literals (using backticks ` `) are a modern way to create strings in JavaScript. They make code cleaner, more readable, and easier to maintain compared to traditional string concatenation.

I) What Are Template Literals

Template literals are a modern way to create strings in JavaScript using backticks ` ` instead of quotes (' or "). They allow you to easily include variables and expressions inside a string.

II) Basic Syntax

let name = "John";
let message = `Hello ${name}`;
console.log(message); // Output: Hello John

👉 Use ${} to insert variables or expressions inside the string.

III) Compare: Old Concatenation vs Template Literals

// Old way (concatenation)
let name = "John";
let age = 25;
let msg1 = "Hello " + name + ", you are " + age + " years old.";

// Modern way (template literals)
let msg2 = `Hello \({name}, you are \){age} years old.`;

👉 Template literals remove + and make code cleaner.

IV) Readability Improvement

  • No need for multiple + operators

  • Easier to read and understand

  • Looks more natural (like normal sentences)

let product = "Laptop";
let price = 50000;

// Clean and readable
let text = `The price of \({product} is ₹\){price}.`;

👉 Especially useful for long or dynamic strings.

V) Multi-line Strings

let text = `This is line 1
This is line 2
This is line 3`;

console.log(text);

👉 No need for \n or concatenation.

VI) Using Expressions

let a = 10;
let b = 20;

let result = `Sum is ${a + b}`;
console.log(result); // Output: Sum is 30

3) Embedding Variables in Strings

Embedding variables in strings means inserting variable values directly inside a string instead of joining them using +. In modern JavaScript, this is done using template literals with backticks ` ` and the ${} syntax.

I) Basic Idea

  • Use backticks ` ` to create the string

  • Use ${variable} to insert values

let name = "John";

let message = `Hello ${name}`;
console.log(message); // Output: Hello John

II) Multiple Variables

You can embed more than one variable easily.

let name = "John";
let age = 25;

let message = `Hello \({name}, you are \){age} years old.`;
console.log(message);

III) Compare with Old Method

// Old way
let msg1 = "Hello " + name + ", you are " + age + " years old.";

// New way
let msg2 = `Hello \({name}, you are \){age} years old.`;

👉 Template literals are cleaner and easier to read.

IV) Using Expressions

You can also use calculations or logic inside ${}.

let price = 100;
let quantity = 2;

let total = `Total price is ${price * quantity}`;
console.log(total); // Output: Total price is 200

V) Why It’s Useful

  • Improves readability

  • Reduces errors (no missing spaces or +)

  • Makes dynamic strings easy to create


4) Multi-line Strings

Multi-line strings allow you to write text across multiple lines without using special characters like \n or string concatenation. In JavaScript, this is done using template literals (backticks ` `).

I) Basic Idea

  • Use backticks instead of quotes

  • Write text on multiple lines directly

let text = `This is line 1
This is line 2
This is line 3`;

console.log(text);

II) Output

This is line 1
This is line 2
This is line 3

III) Compare with Old Method

// Old way
let text1 = "This is line 1\n" +
            "This is line 2\n" +
            "This is line 3";

// Modern way
let text2 = `This is line 1
This is line 2
This is line 3`;

👉 Template literals are much cleaner and easier to read.

IV) With Variables

You can also include variables inside multi-line strings.

let name = "John";

let message = `Hello ${name},
Welcome to our platform.
Have a great day!`;

console.log(message);

V) Why It’s Useful 💡

  • No need for \n or +

  • Improves readability

  • Great for writing long text (emails, messages, templates)


5) Use cases in modern JavaScript

Template literals are widely used in modern JavaScript because they make strings more powerful, readable, and flexible. They are not just for simple text—they are used in real applications like web development, APIs, and dynamic UI generation.

I) Dynamic Messages (User-Friendly Text)

Template literals are commonly used to create dynamic messages based on variables.

let user = "John";
let status = "active";

let message = `Hello \({user}, your account is \){status}.`;
console.log(message);

👉 Useful in dashboards, notifications, and alerts.

II) Building HTML Templates (Frontend Development)

Very commonly used in web development to generate HTML dynamically.

let title = "Product List";

let html = 
`<div>
    <h1>${title}</h1>
    <p>Welcome to our store</p>
  </div>`;

console.log(html);

👉 Makes UI creation cleaner and easier.

III) API Responses / Data Display

Used to format data coming from APIs.

let product = {
  name: "Laptop",
  price: 50000
};

let output = `Product: \({product.name}, Price: ₹\){product.price}`;
console.log(output);

👉 Helps in displaying backend data in readable format.

IV) Multi-line Content (Emails, Messages, Templates)

let name = "Alice";

let email = `Dear ${name},

Thank you for registering with us.
We are happy to have you onboard.

Regards,
Team`;

console.log(email);

👉 Very useful for email templates and long messages.

V) Expressions and Calculations

You can directly perform calculations inside strings.

let price = 100;
let qty = 3;

let bill = `Total Bill: ₹${price * qty}`;
console.log(bill);

VI) Conditional Rendering (Simple Logic)

You can even use ternary operators inside template literals.

let age = 18;

let result = `You are ${age >= 18 ? "eligible" : "not eligible"}`;
console.log(result);

VII) Logging and Debugging

Useful for clean and structured logs.

let id = 101;
let status = "success";

console.log(`Request ID: \({id} | Status: \){status}`);

VIII) Why It’s Important in Modern JavaScript

  • Improves readability and maintainability

  • Reduces complex string concatenation

  • Makes code clean and professional

  • Widely used in React, Node.js, and APIs


summary

Template literals in JavaScript provide a modern and cleaner way to work with strings using backticks. They allow easy embedding of variables, support multi-line strings, and improve readability compared to traditional string concatenation. Widely used in real-world applications, they make code more maintainable, flexible, and easier to understand.