Skip to main content

Command Palette

Search for a command to run...

Template Literals in JavaScript

Updated
•2 min read•View as Markdown
Template Literals in JavaScript
M
Just a tech guy

“Writing strings shouldn’t feel messy”

Working with strings is common in JavaScript — especially when you need to combine variables with text.

But traditional string concatenation quickly becomes hard to read.


The Problem with Traditional String Concatenation

let name = "Mohit";
let age = 24;

let message = "My name is " + name + " and I am " + age + " years old.";

console.log(message);

This works, but as the string grows:

  • readability decreases

  • formatting becomes harder

  • easy to make mistakes


Template Literals: The Modern Way

Template literals were introduced in ES6 (ECMAScript 2015).

They use backticks ( ) instead of quotes.

let message = `My name is Mohit`;

String Interpolation

Instead of using +, you can directly insert variables using:

${variable}

Example:

let name = "Mohit";
let age = 24;

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

console.log(message);

Multi-line Strings

With traditional strings:

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

With template literals:

let text = `Line 1
Line 2
Line 3`;
  • No special characters needed

  • Much more readable


Expressions Inside Template Literals

You can also run expressions inside ${}:

let a = 10;
let b = 20;

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

Output :

30

Real-World Use Cases

1. Dynamic Messages

let user = "Mohit";
console.log(`Welcome back, ${user}`);

2. API URLs

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

3. HTML Templates (Frontend)

let name = "Mohit";

let html = `<div>
  <h1>Hello, ${name}</h1>
</div>`;

Before vs After (Quick Comparison)

Traditional Template Literals
"Hello " + name Hello ${name}
Hard to read Clean and readable
Needs \n for new lines Supports multi-line directly

Final Thought

Template literals make string handling in JavaScript more readable and maintainable by allowing direct interpolation and clean formatting.