DEV Community

Cover image for Template Literals in JavaScript
Bhupesh Chandra Joshi
Bhupesh Chandra Joshi

Posted on

Template Literals in JavaScript

Template Literals in JavaScript: Writing Cleaner and Smarter Strings

Modern JavaScript has evolved significantly to improve developer productivity and code readability. One feature that dramatically improved how developers work with strings is Template Literals.

Before ES6 (ECMAScript 2015), developers relied on string concatenation using the + operator, which often made code messy and hard to read. Template literals solved this problem by introducing a more intuitive way to build strings.

In this article, we will explore:

  • Problems with traditional string concatenation
  • Template literal syntax
  • Embedding variables in strings (String Interpolation)
  • Multi-line strings
  • Real-world use cases in modern JavaScript

The Problem with Traditional String Concatenation

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

Example (Old Approach)

const name = "Bhupesh";
const profession = "JavaScript Developer";

const message = "Hello, my name is " + name + " and I am a " + profession + ".";
console.log(message);
Enter fullscreen mode Exit fullscreen mode

Output

Hello, my name is Bhupesh and I am a JavaScript Developer.
Enter fullscreen mode Exit fullscreen mode

Issues with this approach

  1. Poor readability when many variables are involved
  2. Hard to maintain in long strings
  3. Error-prone, especially when mixing quotes and variables
  4. Multi-line strings are difficult

Example of a complex concatenation:

const product = "Laptop";
const price = 80000;

const description = "Product: " + product +
                    ", Price: ₹" + price +
                    ", Available in stock.";

console.log(description);
Enter fullscreen mode Exit fullscreen mode

When applications grow, such code becomes difficult to manage.


Template Literals Syntax

Template literals were introduced in ES6 and use backticks () instead of quotes.

Inside template literals, JavaScript allows embedding expressions using:

${expression}
Enter fullscreen mode Exit fullscreen mode

Basic Example

const name = "Bhupesh";
const profession = "JavaScript Developer";

const message = `Hello, my name is ${name} and I am a ${profession}.`;

console.log(message);
Enter fullscreen mode Exit fullscreen mode

Output

Hello, my name is Bhupesh and I am a JavaScript Developer.
Enter fullscreen mode Exit fullscreen mode

The syntax is much cleaner and easier to read.


Before vs After (Comparison)

Traditional Concatenation

const user = "Bhupesh";
const course = "JavaScript";

const text = "User " + user + " is learning " + course + ".";
Enter fullscreen mode Exit fullscreen mode

Template Literals

const user = "Bhupesh";
const course = "JavaScript";

const text = `User ${user} is learning ${course}.`;
Enter fullscreen mode Exit fullscreen mode

Result: Same output, but the template literal version is significantly cleaner.


Embedding Variables in Strings (String Interpolation)

Template literals allow variables and expressions to be directly inserted inside strings.

Example

const price = 500;
const tax = 0.18;

const total = `Total amount after tax: ${price + price * tax}`;

console.log(total);
Enter fullscreen mode Exit fullscreen mode

Output

Total amount after tax: 590
Enter fullscreen mode Exit fullscreen mode

You can embed:

  • Variables
  • Mathematical expressions
  • Function calls

Example with function:

function greet(name) {
  return `Hello ${name}, welcome to JavaScript!`;
}

console.log(greet("Bhupesh"));
Enter fullscreen mode Exit fullscreen mode

Multi-line Strings

Before template literals, multi-line strings required awkward formatting.

Old Approach

const text = "JavaScript is powerful.\n" +
             "It runs in browsers.\n" +
             "It powers modern web applications.";

console.log(text);
Enter fullscreen mode Exit fullscreen mode

With Template Literals

const text = `JavaScript is powerful.
It runs in browsers.
It powers modern web applications.`;

console.log(text);
Enter fullscreen mode Exit fullscreen mode

This makes template literals extremely useful for:

  • HTML templates
  • Emails
  • Logs
  • Documentation strings

Real-World Use Cases in Modern JavaScript

Template literals are heavily used in real-world applications.


1. Dynamic HTML Generation

Frontend developers frequently generate HTML dynamically.

const username = "Bhupesh";
const role = "Admin";

const html = `
<div class="user-card">
  <h2>${username}</h2>
  <p>Role: ${role}</p>
</div>
`;

console.log(html);
Enter fullscreen mode Exit fullscreen mode

This approach is commonly used in React, Vue, and vanilla JavaScript UI rendering.


2. Logging and Debugging

Template literals simplify debugging.

const api = "/users";
const status = 200;

console.log(`API endpoint ${api} responded with status ${status}`);
Enter fullscreen mode Exit fullscreen mode

Instead of:

console.log("API endpoint " + api + " responded with status " + status);
Enter fullscreen mode Exit fullscreen mode

3. Building API URLs

const userId = 45;

const url = `https://api.example.com/users/${userId}`;

console.log(url);
Enter fullscreen mode Exit fullscreen mode

4. Generating SQL Queries (Backend Example)

In Node.js applications:

const userId = 10;

const query = `SELECT * FROM users WHERE id = ${userId}`;
Enter fullscreen mode Exit fullscreen mode

Note: In production, always use parameterized queries to prevent SQL injection.


Visualization: String Interpolation Concept

Imagine template literals as a string template with placeholders.

Template:  Hello ${name}, welcome to ${platform}

Variables:
name = Bhupesh
platform = JavaScript

Final Output:
Hello Bhupesh, welcome to JavaScript
Enter fullscreen mode Exit fullscreen mode

The ${} section works like a dynamic placeholder that gets replaced with actual values.


When Should You Use Template Literals?

Template literals should be preferred when:

  • Combining strings with variables
  • Writing multi-line text
  • Creating dynamic HTML
  • Logging values
  • Generating dynamic URLs

They improve:

  • Readability
  • Maintainability
  • Developer productivity

Key Takeaways

  • Template literals were introduced in ES6.
  • They use backticks () instead of quotes.
  • ${} allows string interpolation.
  • They support multi-line strings.
  • Widely used in modern frontend and backend JavaScript.

Final Thoughts

Template literals may seem like a small feature, but they significantly improve the way JavaScript developers write and manage strings. Cleaner syntax leads to more readable code, fewer bugs, and faster development.

For developers building modern web applications with JavaScript, Node.js, or frameworks like React, template literals are an essential part of everyday coding.


Top comments (0)