Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Improve readability with Template Literals

Published
β€’5 min read
Template Literals in JavaScript
P

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².

Introduction

Strings are one of the most commonly used data types in JavaScript. In the early days of JavaScript, developers relied on string concatenation using the + operator to build dynamic strings. While functional, this approach quickly becomes difficult to read and maintain as applications grow.

With the introduction of ES6 (ECMAScript 2015), JavaScript provided a better alternative: Template Literals. They simplify string handling, improve readability, and allow embedding expressions directly inside strings.

This article explores template literals in depth, from basics to real-world usage.

Problems with Traditional String Concatenation

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

Example: Basic Concatenation

const name = "Prakash";
const age = 21;

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

This works, but introduces several issues:

  • Reduced readability

  • Repetitive syntax

  • Higher chance of missing quotes or operators

Example: Complex UI String

const product = "Laptop";
const price = 50000;

const html = "<div>" +
               "<h1>" + product + "</h1>" +
               "<p>Price: β‚Ή" + price + "</p>" +
             "</div>";

Problems:

  • Structure is hard to visualize

  • Debugging becomes difficult

  • Not scalable for larger templates

Example: Multi-line Strings

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

Problems:

  • Use of \n reduces clarity

  • Not visually aligned with output

  • Harder to maintain

What are Template Literals?

Template literals are string literals enclosed by backticks (`) instead of single (') or double (") quotes.

They provide:

  • Built-in string interpolation

  • Multi-line string support

  • Embedded expressions

  • Cleaner syntax

Template Literal Syntax

const str = `This is a template literal`;

Key distinction:

  • " " and ' ' β†’ traditional strings

  • ` ` β†’ template literals

Embedding Variables (String Interpolation)

Instead of concatenation, template literals allow embedding variables using ${}.

const name = "Prakash";
const age = 21;

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

Benefits:

  • Eliminates +

  • Improves readability

  • Makes strings more natural to write

Embedding Expressions

Template literals allow execution of JavaScript expressions inside ${}.

const a = 10;
const b = 20;

console.log(`Sum is ${a + b}`);
console.log(`Random number: ${Math.random()}`);
console.log(`Is adult: ${age >= 18}`);

This makes template literals highly flexible and powerful.

Multi-line Strings

Template literals support multi-line strings without special characters.

Traditional approach

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

Template literal approach

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

Advantages:

  • Cleaner syntax

  • Matches actual output visually

  • Easier to edit and maintain

Real-World Use Cases

1. Dynamic HTML Generation

const user = {
  name: "Prakash",
  role: "Developer"
};

const card = `
  <div class="card">
    <h2>${user.name}</h2>
    <p>${user.role}</p>
  </div>
`;

Used in:

  • Frontend rendering

  • Server-side templates

  • Email generation

2. Logging and Debugging

const id = 101;
const status = "success";

console.log(`Request \({id} completed with status: \){status}`);

Improves clarity in logs and debugging.

3. API Responses

function greet(user) {
  return `Welcome \({user.name}, your balance is β‚Ή\){user.balance}`;
}

4. SQL Query Construction (with caution)

const table = "users";

const query = `SELECT * FROM ${table}`;

Note: Avoid direct interpolation in production queries. Use parameterized queries to prevent SQL injection.

5. Conditional Rendering

const isLoggedIn = true;

const message = `User is ${isLoggedIn ? "logged in" : "not logged in"}`;

Before vs After Comparison

Before (Concatenation)

const name = "Prakash";
const msg = "Hello " + name + ", welcome to our platform!";

After (Template Literal)

const msg = `Hello ${name}, welcome to our platform!`;

Before (Complex Structure)

const html = "<ul>" +
               "<li>" + item1 + "</li>" +
               "<li>" + item2 + "</li>" +
             "</ul>";

After (Cleaner Version)

const html = `
  <ul>
    <li>${item1}</li>
    <li>${item2}</li>
  </ul>
`;

Readability Improvement

Template literals significantly improve:

  • Code clarity

  • Maintainability

  • Team collaboration

  • Debugging efficiency

They reduce visual noise and make code closer to natural language.

Advanced Concept: Tagged Templates

Template literals can be customized using tagged functions.

function highlight(strings, value) {
  return `\({strings[0]}**\){value}**${strings[1]}`;
}

const result = highlight`Hello ${"Prakash"}!`;
console.log(result);

Output:

Hello **Prakash**!

Use cases:

  • Styling libraries (e.g., styled-components)

  • Internationalization

  • Security sanitization

Common Mistakes

1. Using quotes instead of backticks

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

// Correct
const msg = `Hello ${name}`;

2. Overcomplicating expressions

// Hard to read
`${user.age > 18 ? user.name.toUpperCase() : "Minor"}`

Better approach:

const displayName = user.age > 18 ? user.name.toUpperCase() : "Minor";
`${displayName}`

Why Template Literals Matter in Modern JavaScript

Template literals are widely used in:

  • React applications

  • Node.js backends

  • Logging systems

  • API responses

  • Dynamic UI rendering

They are considered standard practice in modern JavaScript development.

Conclusion

Template literals are more than a syntactic improvement. They fundamentally change how developers work with strings by making code cleaner, more expressive, and easier to maintain.

They:

  • Replace complex concatenation

  • Enable dynamic string creation

  • Improve readability

  • Support scalable development

Adopting template literals is essential for writing modern JavaScript.


I write articles on blog.prakashtsx.com and also post development-related content on:

JavaScript

Part 2 of 11

In this series of blogs I have written some interesting concepts related to JavaScript.

Up next

JavaScript Operators: The Basics You Need to Know

Operators in JavaScript

More from this blog

Learn with Prakash

36 posts

My name is 𝐏𝐫𝐚𝐀𝐚𝐬𝐑 and I talk about 𝗧𝗲𝗰𝗡-𝐊𝐧𝐨𝐰π₯𝐞𝐝𝐠𝐞, π—ͺπ—²π—―π——π—²π˜ƒ, π——π—²π˜ƒπ—’π—½π˜€ and π—Ÿπ—Άπ—³π—²π˜€π˜π˜†π—Ήπ—².