Composing Messages with Template Literals
Introduction
Welcome back to Storing and Calculating with JavaScript Values! This is the last lesson of the course, and it ties together everything we have done in it.
In the previous lesson we built sentences by joining pieces of text with +. It works, but it is fiddly: a simple greeting needs three pieces, two plus signs, and four quotation marks, and one forgotten space spoils the result. JavaScript offers a cleaner way to write the same thing, and once we have seen it, we will rarely want to go back.
In this lesson, we will learn how to:
- Write a template literal, a piece of text wrapped in backticks instead of quotation marks.
- Drop a stored value straight into the text with a placeholder,
${}. - Put a calculation inside a placeholder so the result appears mid-sentence.
- Make template literals our default way of composing a message.
By the end, we will have a short receipt that names the customer, counts the cups, and works out the total, all in two readable lines.
The Trouble with Plus
Let's look again at the greeting from last lesson:
It prints exactly what we want:
But read the code rather than the output. To see the sentence, we have to mentally remove the quotation marks, remove the plus signs, and paste the name into the gap. For a three-piece greeting that is manageable. For a receipt line with three or four values in it, the pluses and quotation marks start to outnumber the words, and every join is a place to lose a space. What we would really like is to write the sentence as a sentence and simply mark where the values go.
Meet the Backtick
JavaScript lets us do exactly that with a template literal. A template literal is text, like the text we have been writing all along, but it is wrapped in backticks rather than double quotation marks. The backtick is a small slanting mark that sits on its own key - usually at the top left of the keyboard, sharing a key with the tilde ~, though its position varies from one keyboard layout to another. It is not the same as a single quotation mark ', so it is worth looking twice.
Here is a template literal with nothing special in it yet:
Wrapped in backticks, the text prints just as it would in double quotation marks:
On its own, that is no improvement. The backticks earn their keep with the next idea.
Placing a Value with ${}
Inside a template literal, we can open a placeholder with ${, write the name of a variable, and close it with }. When the program runs, JavaScript replaces the whole placeholder with the value stored under that name:
JavaScript looks up customerName, drops Alex into the sentence where the placeholder was, and prints the result:
Let's compare this line with the + version. The sentence is written in one piece, in order, with the comma, the space, and the exclamation mark all typed exactly where they belong. There are no joins to manage, and the spacing sits right there in the sentence where we can see it - the only thing that is not ordinary text is the placeholder, and its ${ and } make it easy to spot. Reading the code, we can see the sentence.
Two small rules keep placeholders working. The $ and the { go together, with nothing between them, and every ${ needs its closing }. And placeholders only work inside backticks: in double quotation marks, ${customerName} is just ordinary characters, and JavaScript prints it as written, braces and all.
Several Values in One Message
A template literal can hold as many placeholders as we like, and a placeholder can hold a number just as easily as text:
Each placeholder is replaced by its value, and a number simply appears as its digits:
Notice that the template literal can start with a placeholder. There is no need for a piece of fixed text first; the sentence begins wherever we begin it.
A Calculation Inside the Braces
A placeholder does not have to be just a name. It can hold any expression - anything JavaScript can work out to a single value - and the result is what appears in the text:
JavaScript works out 4.5 * 3 first, gets 13.5, and places that in the sentence:
This is the same rule we met with = and with console.log: the expression is worked out first, and the value it produces is what gets used. For anything more than a short calculation, though, it is still kinder to the reader to store the result under a good name first and put the name in the placeholder.
Which Should We Use?
We now have three ways to get a value into a message: commas inside console.log, joining with +, and template literals. From here on, template literals are our default whenever a message mixes fixed text with values. They read like the sentence they produce, they put spaces and punctuation under our control, and they take a calculation in their stride.
The other two do not disappear. Commas are still the quickest way to print a label next to a value while we are checking that a program works, and joining with + appears in a great deal of JavaScript we will read, so it pays to recognise it. But when we sit down to compose a message for someone to read, we reach for the backticks.
The Full Program
Here is everything from this lesson in one file:
When we click Run, the first two lines come out identical - the + version and the template literal produce exactly the same text - followed by a sentence with two values in it and one with a calculation:
Read the last two console.log lines once more. Each is a sentence with a couple of clearly marked gaps, and the output is that sentence with the gaps filled in. That is what composing a message should feel like.
Conclusion and Next Steps
Fantastic work! In this lesson, we learned that a template literal is text wrapped in backticks, that a placeholder written as ${} drops a stored value - or the result of a calculation - straight into that text, and that this is now our default way to compose a message.
That also completes the whole course. We can now change a stored value with let, calculate with the four arithmetic operators and parentheses, join text with +, and compose a message with a template literal. The last set of practice tasks is next, and after that, a new course where we learn to ask a value what kind it is, convert between text and numbers, and compare values with one another. Let's finish strong!
