ES6: All Hail, Template Literals

Mentally Friendly

By Wayne Dunkley (Front-end Developer)

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.

let multi_line = `This is a multi-line comment,
spread over 3
lines`
console.log(multi_line);---This is a multi-line comment,
spread over 3
lines

Once used together you can clearly see the difference in ease of use and readability that template literals offer. The below example shows a comparison of the old method for constructing strings and the new method using template literals.

var username = 'Dave'
var current = 35
var won = 100
var bonus = 2
var template = `Hello ${ username },
your new balance is ${ current + won * bonus } points.`
var string = "Hello " + username + ",\n your new balance is " + ( current + won * bonus ) + " points."console.log(template);
console.log(string);
---Hello Dave,
your new balance is 235 points.

Template Literals not only make strings with variables and embedded expressions easier to write, but with their increased readability will undoubtably make it easier to identify errors before they are output to screen.

Mentally Friendly

Written by

Designing for wellbeing outcomes across products, teams and policy.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade