emplate Literals are a modern (ES6) way to create strings using backticks (` `).
They allow:

  • Multi-line strings
  • Variable interpolation
  • Embedding expressions
  • Tagged templates
  • Cleaner, more readable code

1. Basic Syntax

Template literals use backticks (not quotes).

const message = `Hello World!`;

2. String Interpolation (Embedding Variables)

Use ${...} inside backticks.

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

No need for string concatenation:

"Hello " + name + "!"

Template literals make this cleaner.

3. Embedding Expressions

The ${} placeholder can contain any JavaScript expression:

arithmetic

const a = 10;
const b = 20;const result = `Sum: ${a + b}`;
console.log(result); // Sum: 30

function calls

function priceAfterTax(price) {
return price * 1.15;
}
const finalPrice = `Final: ${priceAfterTax(100)}`;
console.log(finalPrice); // Final: 115

ternary operator

const isLoggedIn = true;
const msg = `Status: ${isLoggedIn ? "Logged In" : "Guest"}`;
console.log(msg);

4. Multi-line Strings

Template literals support real multi-line text (no \n needed).

const text = `
Line 1
Line 2
Line 3
`;
console.log(text);

Equivalent using old method (hard to read):

"Line 1\nLine 2\nLine 3\n"

5. Embedding HTML (Common in JS/React/Node)

const title = "Dashboard";
const html = `
<div>
<h1>${title}</h1>
<p>Welcome to your dashboard.</p>
</div>
`;
console.log(html);

6. Template Literals in Loops

const products = ["Phone", "Laptop", "Tablet"];

products.forEach((p, i) => {
console.log(`Product ${i + 1}: ${p}`);
});

7. Tagged Template Literals (Advanced Feature)

Tagged templates allow you to process the template literal with a function.

Basic example:

function myTag(strings, ...values) {
console.log(strings); // array of string chunks
console.log(values);  // array of injected values
}
const name = "Zaman";
const age = 25;myTag`Name: ${name}, Age: ${age}`; 

Output:

["Name: ", ", Age: ", ""]
["Zaman", 25]

Real use case: escaping HTML

function escapeHTML(strings, ...values) {
return strings.reduce((result, str, i) => {
let value = values[i] || "";value = String(value) .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;");return result + str + value;
}, "");
}

const userInput = "<script>alert('xss')</script>";

const safe = escapeHTML`User says: ${userInput}`;
console.log(safe);

Categorized in:

Javascript ES6,