One of my favourite additions to ES6 is Template Literals, or Template Strings as they were previous known. We all know how painful it is to construct a String made up of text, variables and expressions. There are single quotes, double quotes and plus signs all over the place. See the following code example to be reminded of the horror.

let string = "Welcome " + name + ", your balance is " + ( oldValue + newValue );

Template literals are ES6's answer to this outdated headache. They are defined using back-ticks ` ` and allow us to construct strings with embedded expressions and variables as you would in templating libraries such as Jade or Handlebars.

Placeholders are used to include variables into the template literal are identified using the dollar sign and curly braces ${}. These are evaluated and concatenated to a single string before they are embedded. The above example using Template Literals looks like this.

let string = `Welcome ${name}, your balance is ${oldValue + newValue}`

Placeholders may also contain expressions that will be evaluated before being parsed to a string and embedded.

let a = 5

let b = 4 let total = `Your total balance is ${ a + b }` console.log(total); --- Your total balance is 9

Multi-line strings

Template literals can not only work over multiple lines, but will also insert any recognised new lines into the outputted string.