Template Literals in ES2015

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

Another great and super useful addition to the JavaScript language are template literals (or template strings). Essentially, they allow you to use expressions inside string literals which have quite a few interesting use-cases.

Template literals are denoted by back-tick characters ( ) and place-holders are denoted by the dollar sign and curly braces (${}). As I said earlier these template literals have a few interesting use-cases, the first one being that we can achieve string concatenation a lot easier by using the place holders:

const name = 'Steve';
console.log('Hello there, ' + name + '!');
console.log(`Hello there, ${name}!`);

It's clear that the second console.log statement is a lot simpler to use.

And if we think about this a bit more it's clear how we can pass variables to HTTP calls dynamically as opposed to using string concatenation:

http.get(`http://api.com/product?name=${name}&colour=${colour}`);

The above is something that I personally use quite a lot and I like the power that the template literal syntax gives.

Since template literals allow for JavaScript expressions we can also call methods within the expressions. Therefore having such a statement is perfectly valid: console.log(${name.toLowerCase()});.

The template literal syntax also allows us to have multiline strings and allows for having expressions in the statement:

console.log(`This
is
a multiline

calculator:
${3 * 3}

Quite cool!
`
);

/* returns
This
is
a multiline

calculator: 9

Quite cool!
*/