Jorge Valle

Jorge Valle

Jorge Valle is a front end developer with a particular passion for, and expertise in, JavaScript and user interfaces. Lately, he's also been diving into machine learning.

Template literals in ES6

The Backtick

Arguably one of the most useful additions to ECMAScript 6 have been template literals.

Strings have been traditionally delimited by two characters: the single quote, and the double quote.

Now, we have a third: the backtick.

Any string enclosed in backticks is considered a template literal.

Multiple Lines

Previous to ES6, if we wanted to have multi-line strings, we'd have to resort to using concatenation.

With template literals, our string can span as many lines as we want, and it won't break up.

This makes working with multi-line strings much easier and much more readable.

Interpolated Values

Before template literals, embedding dynamic values into strings was a messy endeavour. There was no way to pass such values right onto the string, so strings would have to be broken up - and then concatenated with the values - in order to insert variables.

Now, with template literals, we can do string interpolation. By interpolation we mean the passing and correct rendering of dynamic values right onto the string. They will be correctly interpreted, provided they are enclosed in the correct syntax of dollar sign and curly braces.

Interpolated Expressions

Interpolation doesn't stop at values: expressions can also be interpolated. I end up using this syntax quite a lot in practice, returning function values with ease.

Conclusion

I love template literals. They feel a lot like using templating engines such as Pug, but in native JS.

Remember, template literals are part of the ES6 specification, so they are not yet fully supported across all browsers. If you want to use them client-side in producton, remember to transpile first through Babel or similar.


Books, patrons and coffee in Caffè San Marco, Trieste