Template literals
A template literal is a string in backticks `. You can insert values right in the middle of the text and spread it over several lines. Almost any text a program builds from data is most convenient to write this way.
Inserting a value
Inside a template literal, ${...} is replaced with the value of whatever is in the braces:
const name = 'Anna';
console.log(`Hello, ${name}!`); // Hello, Anna!Without a template you would glue the parts with a plus: 'Hello, ' + name + '!'. The more parts there are, the harder such code is to read.
Expressions
${...} can hold any expression — a calculation, a function or method call:
const price = 12;
const count = 3;
console.log(`Total: $${price * count}`); // Total: $36
console.log(`Name: ${'oleg'.toUpperCase()}`); // Name: OLEGAn expression is any piece of code that produces a value. In $${...} the first $ is an ordinary character.
Multi-line text
A line break inside backticks is kept in the result. Ordinary quotes cannot do this — there you would have to write the break as \n:
const message = `Order accepted.
Delivery is on its way.`;
console.log(message);
// Order accepted.
// Delivery is on its way.A condition inside a template
The ternary operator condition ? yes : no inserts one of two pieces of text. It is handy for short choices:
const count = 1;
console.log(`Your cart has ${count} ${count === 1 ? 'item' : 'items'}`); // Your cart has 1 itemFor complex logic, compute the value in a separate variable first and insert that into the template.
A template from an array
Inside ${...} you can call map() and join() — this is how a list or a piece of markup is built from an array:
const items = ['tea', 'coffee'];
const list = items.map((item) => `- ${item}`).join('\n');
console.log(list);
// - tea
// - coffeeTagged templates
If you write a function name before a template, the function receives the text parts and the inserted values separately. Libraries use such tagged templates, for example to build queries safely. The built-in tag String.raw keeps backslashes as they are:
console.log(String.raw`C:\new\table`); // C:\new\tableCommon mistake
The ${...} insertion works only in backticks. In single or double quotes it stays plain text:
const name = 'Anna';
console.log('Hello, ${name}'); // Hello, ${name}
console.log(`Hello, ${name}`); // Hello, Anna