JavaScript(JS) Template Literals

Template literals, introduced in ES6 (ECMAScript 2015), are a new type of string literal in JavaScript that allow you to embed expressions and variables directly in a string.

Here's an example of using template literals to embed a variable in a string:

refer ‮tfigi:ot‬idea.com
let name = 'John';
console.log(`Hello, ${name}!`);

In this example, the template literal syntax is denoted by the backtick () characters that enclose the string. The${name}expression inside the string is evaluated as the value of thenamevariable, resulting in the outputHello, John!`.

Template literals can also be used to embed expressions and statements inside a string:

let x = 10;
console.log(`The value of x is ${x}, and its square is ${x * x}.`);

In this example, the expressions ${x} and ${x * x} are evaluated and embedded in the string, resulting in the output The value of x is 10, and its square is 100..

Template literals can also span multiple lines and include whitespace and formatting characters:

let message = `
  This is a multiline message
  with ${2 + 2} lines
  and some formatting
  characters, like tabs:
  
  \t* Item 1
  \t* Item 2
`;

console.log(message);

In this example, the template literal spans multiple lines and includes formatting characters like tabs (\t). The expression ${2 + 2} is evaluated as 4 and embedded in the string, resulting in the output:

This is a multiline message
with 4 lines
and some formatting
characters, like tabs:

    * Item 1
    * Item 2