Template Literals in JavaScript

Template literals are a feature introduced in ES6 (ECMAScript 2015) that provide a more powerful and flexible way to work with strings. They allow for string interpolation, multiline strings, and the inclusion of expressions within a string.

Key Features:

  1. String Interpolation:

  2. Multiline Strings:

  3. Embedding Expressions:

  4. Tagged Template Literals:

Example of Template Literals in Action:

let firstName = 'John';
let lastName = 'Doe';
let age = 25;

let message = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;
console.log(message);  // Output: "Hello, my name is John Doe and I am 25 years old."

// Multiline string
let address = `123 Main St
City, Country
Postal Code`;
console.log(address);

// Using expressions in template literals
let price = 100;
let discount = 20;
let finalPrice = `The final price after ${discount}% discount is $${price - (price * discount / 100)}.`;
console.log(finalPrice);  // Output: "The final price after 20% discount is $80."

Advantages of Template Literals:

In summary, template literals offer a more readable and efficient way to handle strings in JavaScript, especially when working with dynamic data and multiline content.