Template literals
Template literals are a modern and very convenient way to work with strings in JavaScript. They appeared in the ES6 (ECMAScript 2015) standard and let you write multiline strings, embed variables, and expressions right inside the text.
Syntax
Template literals are created not with regular quotes (' or "),
but with backticks - `:
const name = 'Tim';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Tim!"Main features
Interpolation of variables and expressions
You can insert any JavaScript expression inside ${...}:
const a = 5;
const b = 10;
console.log(`Sum: ${a + b}`); // "Sum: 15"
console.log(`In 2 years: ${2025 + 2}`); // "In 2 years: 2027"
console.log(`Random number: ${Math.random()}`);Everything inside
${...}is evaluated, and the result is inserted into the string.
Multiline strings
Previously, you had to write it like this:
const text = 'First line\n' +
'Second line\n' +
'Third line';Now you can simply write:
const text = `
First line
Second line
Third line
`;
console.log(text);Line breaks are preserved automatically.
Nested expressions and function calls
const user = { name: 'Tim', age: 25 };
function greet(u) {
return `Hello, ${u.name}! You are ${u.age} years old.`;
}
console.log(`${greet(user)} Have a nice day!`);Template literals can be used inside expressions
const price = 100;
const message = `Product price: ${price}$`;
console.log(message);Advanced feature - tagged templates
So-called "tagged templates" are a function that processes the template string manually.
Example:
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) =>
`${acc}${str}<b>${values[i] || ''}</b>`, ''
);
}
const name = 'Oleh';
const age = 27;
console.log(highlight`Name: ${name}, Age: ${age}`);
// Output: "Name: <b>Oleh</b>, Age: <b>27</b>"This is a powerful technique for template engines, localization, formatting, and even building SQL queries with injection protection.
Summary
| Feature | Regular strings | Template literals |
|---|---|---|
| Multiline strings | No | Yes |
| Inserting variables | Concatenation via + | Via ${} |
| Calling functions inside | Awkward | Easy |
| Readability | Poor | Excellent |
| Uses quotes | ' or " | ` (backtick) |
Reinforcement example
const product = 'Shirt';
const price = 2500;
const message = `
Product: ${product}
Price: ${price}$
Total with delivery: ${price + 500}$
`;
console.log(message);Result:
Product: Shirt
Price: 2500$
Total with delivery: 3000$Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.