Template literals in JavaScript

What is template literals?

Template literals or template strings are string literals that allows multi-line strings, embedded expressions inside string, string interpolation features with them. Template literals are enclosed by the back-tick (` `).

Multi-line strings using template literals:

Before ES2015
console.log('This is the first line\n' +
'This is the second line');
In ES2015
console.log(`This is the first line
This is the second line`);

String interpolation with expression:

// Normal string concatenation 
console.log('Six plus four equals: ' + (6 + 4) + '.');
// Using template literals
console.log(`Six plus four equals: ${6 + 4}.`);

String interpolation with variable:

// Normal string concatenation 
let age = 24
console.log("I'm " + age + " years old!");
// Using template literals
let age = 24
console.log(`I'm ${age} years old!`);

Tagged template literals:

Tagged templates is the more advanced form of template literals introduced in ES6. This tagged template literals parse template literals with a function. The first parameter of a tag function holds an array of string values. The remaining parameters are extracted from the expression sequentially.

Example of tagged templates

var name = 'Joe Smith';

function getName(strings, name) {
  var str0 = strings[0]; // "My name is: "
  var str1 = strings[1]; // "."

  return `${str0}${name}${str1}`;
}

var result = getName`My name is: ${ name }.`;
console.log(result);
// My name is: Joe Smith.
Share