Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
4 min read
Template Literals in JavaScript

Introduction

When working with strings in JavaScript, developers traditionally relied on string concatenation using the + operator. While it works, it often makes the code messy and hard to read—especially when dealing with variables or multi-line text.

To solve these issues, Template Literals were introduced in ES6 (ECMAScript 2015). They provide a cleaner, more readable, and powerful way to work with strings.


Problems with Traditional String Concatenation

Before template literals, strings were combined using the + operator. This approach had several drawbacks:

  1. Poor Readability
const name = "Radhika";
const age = 17;

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

2. Difficult Multi-line Strings

const text = "This is line one.\n" +
             "This is line two.\n" +
             "This is line three.";
console.log(text);

3. Error-Prone

Missing spaces or quotation marks can easily introduce bugs.


What Are Template Literals?

Template literals are a modern way to create strings using backticks ( ) instead of single (') or double (") quotes. They allow:

  • String interpolation

  • Multi-line strings

  • Embedded expressions

  • Tagged templates

Basic Syntax

const message = `This is a template literal.`;

Embedding Variables (String Interpolation)

With template literals, variables can be embedded directly into strings using ${ }.

🔹 Before (Traditional Method)

const name = "Radhika";
const greeting = "Hello " + name + "!";
console.log(greeting);

🔹 After (Template Literals)

const name = "Radhika";
const greeting = `Hello ${name}!`;
console.log(greeting);

🔹 Embedding Expressions

const a = 5;
const b = 10;

console.log(`The sum of \({a} and \){b} is ${a + b}.`);

Multi-line Strings Made Easy

Template literals allow you to write multi-line strings without using \n.

🔹 Traditional Approach

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

🔹 Using Template Literals

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

Use Cases in Modern JavaScript

1. Generating HTML Templates

const user = {
  name: "Radhika",
  age: 20
};

const html = `
  <div class="card">
    <h2>${user.name}</h2>
    <p>Age: ${user.age}</p>
  </div>
`;

console.log(html);

2. Dynamic URL

const userId = 101;
const url = `https://api.example.com/users/${userId}`;
console.log(url);

3. Conditional Rendering

const isLoggedIn = true;
const message = `User is ${isLoggedIn ? "logged in" : "logged out"}.`;
console.log(message);

4. Localisation and Messages

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

console.log(`The price of \({product} is ₹\){price}.`);

Tagged Template Literals (Advanced)

Tagged templates allow you to parse template literals using a function, enabling powerful custom string processing.

🔹 Example

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    const value = values[i] ? `<strong>${values[i]}</strong>` : "";
    return result + str + value;
  }, "");
}

const name = "Radhika";
const age = 20;

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

🔹 Use Cases

  • Internationalization (i18n)

  • Sanitizing user input

  • styling dynamic content


Comparison: Traditional vs Template Literals

Feature Traditional Concatenation Template Literals
Syntax Uses + operator Uses backticks `
Readability Harder to read Easy to read
Multi-line Strings Requires \n Supported directly
Expression Embedding Not supported Supported via ${}
HTML Templates Messy Clean and structured

Advantages of Template Literals

  • Improved readability

  • Easier variable and expression embedding

  • Native support for multi-line strings

  • Ideal for generating dynamic HTML

  • Supports tagged templates for advanced use cases


Browser Support

Template literals are supported in all modern browsers and Node.js environments. If you need to support very old browsers, consider using Babel for transpilation.


Conclusion

Template literals have revolutionized the way developers work with strings in JavaScript. They replace cumbersome string concatenation with a cleaner and more expressive syntax. From simple variable embedding to advanced tagged templates, they are an essential feature in modern JavaScript development.

If you’re still using the + operator for string concatenation, it’s time to switch to template literals for more readable and maintainable code.

If you found this article helpful, feel free to share it with others and leave your thoughts/feedback in the comments. Happy coding!