Javascript Template literals

With the introduction of JavaScript Template Literals in ECMAScript 6 (ES6), it is now possible to build strings that contain embedded expressions. Without requiring string concatenation or escape characters, it enables you to embed expressions inside string literals using a specific syntax.

Backticks (‘) are used in place of single or double quotes in the syntax for template literals. Expressions that are embedded are denoted by curly braces () and a dollar sign ($) before them. Here’s an illustration:

const name = 'John';
const message = `Hello, ${name}!`;
console.log(message); // output: Hello, John!

The expression $name is evaluated in the aforementioned example, and its value is then added to the string. Using variables or other data sources to generate dynamic strings is now simple.

Additionally, template literals support several lines, making it simpler to construct multi-line strings without the use of escape or concatenation characters:

const message = `This is a
multi-line string`;
console.log(message); // output: This is a
                      //         multi-line string

Additionally, tagged templates are supported by template literals, allowing you to apply a function to the string literals. The embedded expressions are passed as distinct arguments, and the function is given an array of string literals. After processing the values, the function can output a fresh string. Here’s an illustration:

function tag(strings, ...values) {
  console.log(strings); // output: [ 'Hello, ', '!' ]
  console.log(values);  // output: [ 'John' ]
  return `${strings[0]}${values[0]}${strings[1]}`;
}

const name = 'John';
const message = tag`Hello, ${name}!`;
console.log(message); // output: Hello, John!

In the example above, the tag function is used to process the template literal. The strings parameter is an array of string literals, and the values parameter is an array of the values of the embedded expressions. The function returns a new string that is created by concatenating the string literals and values in a custom way.