JavaScript : Template Strings

Template strings, also known as template literals, are a feature introduced in ECMAScript 6 (ES6) that allow for easier string interpolation and multiline strings in JavaScript. They are enclosed by backticks (` `) instead of single or double quotes. Here's how you can use template strings in JavaScript:

1. Basic Usage:


You can create template strings by enclosing text within backticks. Variables or expressions can be embedded within the string using ${...} syntax.


let name = "John";
let age = 30;

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

 

2. Multiline Strings:


Template strings support multiline strings without the need for escape characters like \n.


let multiline = `
  This is a
  multiline
  string.
`;
console.log(multiline);
/*
Output:
  "This is a
   multiline
   string."
*/

 

3. Expression Interpolation:


You can embed expressions within template strings, including function calls and complex expressions.


let a = 10;
let b = 5;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);  // Output: "The sum of 10 and 5 is 15."

 

4. Tagged Templates:


Tagged templates allow you to parse template literals with a function. The function (tag) receives the string parts and interpolated values as arguments, allowing for advanced string manipulation.


function greeting(strings, name) {
  return `${strings[0]} ${name.toUpperCase()}!`;
}

let name = "John";
let result = greeting`Hello, ${name}`;
console.log(result);  // Output: "Hello, JOHN!"

 

5. Nesting Template Strings:


Template strings can be nested within other template strings to create more complex strings.


let name = "John";
let result = `Hello, ${`my name is ${name}`}.`;
console.log(result);  // Output: "Hello, my name is John."

 

Template strings provide a convenient and concise syntax for creating strings in JavaScript, especially when working with dynamic content or multiline text. They enhance readability and maintainability of code compared to traditional string concatenation methods.