Skip to main content

Template Literals in ES2015

1 min read

Older Article

This article was published 9 years ago. Some information may be outdated or no longer applicable.

Template literals (or template strings) landed in JavaScript as one of the most useful additions. They let you drop expressions right inside string literals, which opens up a few interesting use cases.

Template literals are wrapped in back-tick characters ( ) and placeholders use the dollar sign with curly braces (${}). The first big win: string concatenation gets dramatically easier.

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

The second console.log statement is cleaner and faster to type.

Think about passing variables to HTTP calls dynamically, instead of wrestling with string concatenation:

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

I use this pattern constantly. The template literal syntax just strips away the friction.

Since template literals allow JavaScript expressions, you can also call methods within the expressions. So a statement like console.log(${name.toLowerCase()}); is perfectly valid.

Template literals also give us multiline strings and inline expressions:

console.log(`This
is
a multiline

calculator: ${3 * 3}

Quite cool!`);

/* returns
This
is
a multiline

calculator: 9

Quite cool!
*/