Template Literals in ES2015

Template Literals in ES2015

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:


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:

a multiline

calculator: ${3 * 3}

Quite cool!`);

/* returns
a multiline

calculator: 9

Quite cool!

Tamas Piros

Developer Evangelist, experienced Technical Trainer and Google Developer Expert in Web Technologies. Active conference speaker, passionate about the latest & greatest advancements in web technologies.

View Comments
Next Post

Rest Parameters, Spread Operator and Default parameters for Functions

Previous Post

Promise anti-pattern