Joining text with + is easy to get wrong. Say name holds Budi and score holds 80. "Hello" + name + "yourscore" + score looks correct, but it gives HelloBudiyourscore80. Every space is missing, and it is hard to see where the spaces should go.
A template literal makes this much easier. A template literal is a string written between two backticks (`) instead of quote marks. Inside it you can put values directly into the text with ${...}, without joining pieces of text with +. A template literal is like a form whose blanks fill themselves in. The text of the form is the text inside the backticks. Each blank is one ${...}, which JavaScript fills with a value.
Putting values in with ${...}
This code puts two variables into one sentence:
const name = "Budi";
const score = 80;
const message = `Hi ${name}, your score is ${score}.`;
console.log(message); // Hi Budi, your score is 80.
`is the backtick. On most keyboards its key is at the top left, just left of the 1 key. The backtick is not the apostrophe'.${name}is a slot, one of the blanks in the form: a$, an opening curly brace, what goes in it, then a closing curly brace. JavaScript replaces the slot with the value of the variablename, which isBudi.- The text outside the slots is copied as it is, including spaces, commas and full stops.
The result is the same as "Hi " + name + ", your score is " + score + ".", but shorter, and the spaces are easier to check.
A slot can hold any expression
In this code, the slots hold a calculation and a choice, not only a variable's name:
const price = 15;
const quantity = 2;
const score = 80;
console.log(`Total: ${price * quantity}`); // Total: 30
console.log(`Status: ${score >= 75 ? "Passed" : "Not passed"}`); // Status: Passed
- A slot can hold any expression (code that produces a value): a calculation, a function call, and so on.
price * quantityis calculated first, then its result, 30, goes into the text.score >= 75 ? "Passed" : "Not passed"means: ifscoreis 75 or more, use"Passed". Otherwise, use"Not passed". Herescoreholds 80, so the result is"Passed". Thiscondition ? A : Bform comes back in the Conditions lesson.
Backticks, not ordinary quotes
These three lines look alike, but only the last line fills the slot:
const name = "Budi";
console.log("Hello ${name}"); // Hello ${name}
console.log(`Hello {name}`); // Hello {name}
console.log(`Hello ${name}`); // Hello Budi
- Inside ordinary quote marks,
"..."or'...',${name}is just a row of ordinary characters and is not filled in. The line printsHello ${name}, exactly as you typed it. - Without the
$,{name}also stays plain text, even inside backticks. - A slot is filled in only when both of these are there: backticks outside, and
${ }inside.
Text on several lines
This function gives back text on two lines: the title on the first line, the body on the second.
function label(title, body) {
return `${title}:\n${body}`;
}
console.log(label("Note", "Buy coffee"));
// Note:
// Buy coffee
\nis the line break character: a backslash and the letter n, written together inside a string.- A template literal can also be written across several lines: press Enter inside the backticks, and the text moves to a new line too.
- Be careful: when you press Enter, the spaces at the start of the next line become part of the text. Inside a function, the editor usually adds spaces in front of a new line. That is why
\nis safer.
⚠️ Slots that don't fill in, spaces that get in by mistake
- Mistaking the apostrophe for a backtick.
'Hello ${name}'doesn't fill the slot. Look for the backtick key left of the 1. - Forgetting the
$.`Hello {name}`prints{name}as it is. - Extra spaces around
\n."Budi \n Developer"keeps a space at the end of the first line and at the start of the second.
TL;DR: A template literal is a string written between backticks (the key left of the 1), not quote marks. Inside it, a ${...} slot is replaced by a value: in `Hello ${name}`, by the value of the variable name. A slot can hold any expression (code that produces a value), for example ${price * quantity}. Inside ordinary quote marks ${...} is not filled in, and without the $ the slot is plain text. For a line break, use \n or press Enter inside the backticks. When you press Enter, the spaces at the start of the next line become part of the text.
⚡ A ${...} slot inside backticks
Write:
const name = "Budi";
const score = 80;
const message = `Hi ${name}, your score is ${score}.`;
// Hi Budi, your score is 80.
Meaning: A template literal is a string written between two backticks. The backtick is the key left of the 1, not the apostrophe. ${name} is a slot: JavaScript replaces it with the value of the variable name. The text outside the slots, including spaces and commas, is copied as it is.
⚡ A slot can hold a calculation
Write:
console.log(`Total: ${price * quantity}`); // Total: 30
Meaning: A slot can hold any expression (code that produces a value), not only a variable. Say price holds 15 and quantity holds 2. The calculation price * quantity runs first, then its result, 30, goes into the text.
⚡ Ordinary quotes don't fill a slot
Guess first: what does console.log("Hello ${name}") print?
Hello ${name}, exactly as typed. Inside ordinary quote marks, ${name} is just a row of ordinary characters, not a slot.
Meaning: A slot is filled in only when both of these are there: backticks outside, and ${ } inside. Without the $, {name} also stays plain text.