ES6 has two new kinds of literals: template literals and tagged template literals.

  • Template literals are string literals with support for interpolation and multiple lines.
  • Tagged template literals (short: tagged templates): are function calls whose parameters are provided via template literals.

Template literals

This is a new kind of string literal allows to use multiple line strings and expression

Template literals are enclosed by the back-tick `...` character instead of double or single quotes.

Expressions can be indicated by the Dollar sign and curly braces ${...}.

const firstname = 'gns';
console.log(`Hello ${firstname},
How are you?`);
// output
Hello gns,
How are you? 

The above code is equivalent to the below ES5 standard code

var firstname = 'gns';
console.log("Hello " + firstname + ",\nHow are you?");
// output
Hello gns,
How are you?

Example 1

var a = 10, b = 20;
console.log(`Addition value for ${a} and ${b} is ${a+b}`); // Addition value for 10 and 20 is 30
var user = {name: 'gns'};
console.log(`Current User: ${user.name.toUpperCase()}.`); // Current User: GNS.

Tagged template literals

A more advanced form of template literals are tagged template literals. With them you are able to modify the output of template literals using a function. The first argument contains an array of string literals ("Hello " , " world", and "" in this example). The second, and each argument after the first one, are the values of the processed (or sometimes called cooked) substitution expressions ("15" and "50" here). In the end, your function returns your manipulated string. There is nothing special about the name tag in the following example. The function name may be anything you want.

var a = 5;
var b = 10;
function tagFun(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(strings[2]); // ""
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50
  return "Bazinga!";
}
tagFun`Hello ${ a + b } world ${ a * b }`;
// "Bazinga!"

Raw strings

The special raw property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.

function tagFun(strings, ...values) {
  console.log(strings.raw[0]); // "string text line 1 \n string text line 2"
}
tagFun`string text line 1 \n string text line 2`;