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.
