Assembling text with + signs, quotes opened and closed again and spaces forgotten in the middle is one of the most tiring things to write in the language. One backtick in place of the quotes, and the problem is gone.
The template literal drops variables into their place inside the text and keeps line breaks exactly as they were written.
Definition
A template literal is a String written between backticks. Every expression placed between ${ and } is evaluated, converted to text, then inserted at that spot.
const firstName = "Alice";
const seats = 3;
console.log(`Hello ${firstName}, ${seats} seats left.`);
// "Hello Alice, 3 seats left."
console.log("Hello " + firstName + ", " + seats + " seats left.");
// the same result, with four concatenations and two spaces not to forgetThe result is an ordinary string: every usual method applies to it, String.trim(), String.split() or String.replace() just like on any other text.
Text across several lines
The line breaks written inside the template are kept, which saves stacking \n characters inside an unreadable concatenation.
const firstName = "Alice";
const message = `Hello ${firstName},
Your seat is booked.`;
console.log(message.split("\n").length); // 3Indentation is part of the string. A template written inside a function carries the alignment spaces of the code on every line, which shows up immediately in an email or a generated file. Push the text back to the margin, or clean it up afterwards.
What can go between the braces
Any expression: a calculation, a function call, an Ternary operator (?:), another template. Statements, on the other hand, are out: no if, no loop, no variable declaration.
const price = 49.9;
const stock = 0;
console.log(`Total: ${(price * 1.2).toFixed(2)} euros`); // "Total: 59.88 euros"
console.log(`Status: ${stock > 0 ? "in stock" : "sold out"}`); // "Status: sold out"
console.log(`Object: ${{ a: 1 }}`); // "Object: [object Object]"That last line is a reminder that the conversion to text is automatic, and rarely readable for an Object. To show its content, go through JSON and its JSON.stringify method.
Tagged templates
A function placed right before the backtick receives the pieces of text on one side and the values on the other. It can therefore handle each value before the final assembly.
function highlight(parts, ...values) {
return parts.reduce(
(text, part, i) =>
text + part + (values[i] !== undefined ? `**${values[i]}**` : ""),
""
);
}
console.log(highlight`${3} seats left`); // "**3** seats left"This is the mechanism behind the libraries that write CSS or database queries inside a template: the tag sees the values separately from the text, and can escape them before they are glued together.
Frequently asked questions
Should quotes be abandoned?
No. For a fixed string, single or double quotes stay perfectly readable and tell the reader no variable is being inserted. The backtick earns its place as soon as a value has to be dropped in or several lines have to be written, which remains very frequent.
Why does my object show up as [object Object]?
Because the insertion converts the value to text, and the default conversion of an object gives exactly that string. Write JSON.stringify(object) inside the braces, or show the property you actually care about. An array, for its part, converts into its items separated by commas.
Can HTML be built with a template?
Technically yes, and it is a classic security trap. A value typed by a visitor, dropped into a template then assigned to innerHTML, can run code in other people's browsers. Go through textContent for text, or escape the sensitive characters before the insertion.