Template Literals in JavaScript

Template literals were introduced in ES6. Template literals provide us a new way to deal with strings.

  • Introduction to template literals.

  • Multiline strings

  • Interpolation

1. Introduction to template literals.

Template Literals are new feature in ES6 that allows to work with strings in different way. The syntax is simple just use backticks instead of single quotes or double quotes.

const variable = `Hello to template literals`

Template literals are unique because they provide features that normal string built with single/double quotes do not provide:

  1. Template literals provide easy syntax to deal with multiline strings.
  2. Template literals provide easy way to interpolate variables and expressions in strings.

2. Multiline strings.

Before ES6, to render the strings on multiple lines you have to explicitly add \n at the end of each line, for eg:

const variable = 'first line\n' + 'second line'

Template literals makes multiline strings much easier. We have to press enter for a new line and it is rendered in the same way, for eg:

const variable = `first line
second line
third line`
console.log(variable)

It would render the output as :

first line
second line
third line

3. Interpolation

Template provides best way to interpolate the variables and expression into strings.

You can do so by using ${...} syntax

const variable = 'test'
const myString = `something ${variable}` // something test

You can also add expressions inside the ${} like this -

const myString = `something ${1+2+3}` // something 6