Introduced in 2015 with ECMAScript6, template literals let us dynamically construct strings of text and embedded expressions, even multi-line strings of text, in a more elegant way than concatenation.
The syntax is not much different from the old one at first glance:
const newWay = `is cool`;
Can you spot the difference? Instead of single
'’ or double
"” quotes we use backticks
In ES5 you had string concatenation:
const name = 'Jack';
const old = 'My name is '+ name + '.';
+ for both addition and concatenation can be confusing and even lead to unexpected bugs:
In ES5 you had to use the newline character
\n explicitly for line breaks and the
\ character at the end of a line to be able to write multi-line strings. This allows to create a string on two lines:
const concatenation = 'First line\n \
Template literals make multi-line strings simpler. Once a template literal is opened with the backtick, you press enter to create a new line, with no special characters, and it’s rendered as-is:
A not as known feature that comes along with template literals, is the ability to tag them. A tagged template is a function that allows you to parse template literals, which allows us to control the string creation.
The way the tag template works is that you put the name of the function that you want to run against the string before the template. So instead of
function() you have
The tag template is equivalent to the following function call:
hi(['My name is ', '.'], name);
First, we get an array of all the string pieces from our literal. After that, we get all the interpolated values. Here we only have one, the `name`.
So then we would need to change our function to accept these arguments and return the string as we like it:
You can also alter the strings depending on the arguments, which is where the true power of tagged templates comes through.
There are popular libraries like
lit-html using tagged components.
We have learned how template literals make strings easier to handle. They can take care of our variables and embedded expressions with ease. This is much more powerful than the old concatenation of strings and variables. And we also took a look into tagged templates and how they can let us manipulate the template literals before the browser exposes them to the world.
Getting Started Series