HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Template Literals

Template Literals (also called Template Strings) were introduced in ES6. They are literals delimited with backticks (`` ` ``) instead of standard quotes and provide several powerful features for working with text.


Backtick Syntax

To use template literals, you wrap your string in backticks. You can use both single and double quotes inside a template literal without needing escape characters.

let text = `He said "It's a beautiful day"`;
console.log(text); // He said "It's a beautiful day"

Multi-line Strings

One of the biggest advantages of template literals is the ability to write strings across multiple lines without needing special characters like \n.

let poem = `
  The woods are lovely, dark and deep,
  But I have promises to keep,
  And miles to go before I sleep.
`;

Variable Interpolation

Template literals allow you to embed variables and expressions directly into your string using the ${...} syntax. This is much cleaner than traditional concatenation with +.

Traditional Way (+):

let firstName = "Mim";
let lastName = "Akter";

let fullName = "Welcome " + firstName + " " + lastName + "!";

The Template Literal Way:

let firstName = "Mim";
let lastName = "Akter";

let fullName = `Welcome ${firstName} ${lastName}!`;

Expression Evaluation

You can also perform mathematical or logical calculations inside the ${...} placeholders.

let price = 100;
let tax = 0.15;

let total = `Total price: ${price * (1 + tax)}`; 
// Result: Total price: 115
Tip: Template literals are the modern standard in JavaScript. They make code more readable, easier to maintain, and significantly reduce concatenation errors.

HTML Templates

Template literals are perfect for generating HTML dynamically in JavaScript:

let header = "Templates Intro";
let tags = ["template literals", "javascript", "es6"];

let html = `<h2>${header}</h2><ul>`;

for (const x of tags) {
  html += `<li>${x}</li>`;
}

html += `</ul>`;
Note: Replacing variables with real values inside a string is formally called string interpolation.

Key Points to Remember

  • Use backticks (`` ` ``) to define template literals
  • Interpolation: Use ${variable} to embed values
  • Multi-line: Press enter directly inside backticks for new lines
  • You can perform calculations inside ${}
  • Perfect for creating dynamic HTML snippets in JS