Template literals
What template strings are
A template string is a string enclosed in backticks (`, not ' and not ").
const name = 'Alex';
const message = `Hello, ${name}!`;
console.log(message); // Hello, Alex!Inside a template string you can insert variables and expressions using
${ ... }.
1. Main difference - variable substitution
Before ES6:
const name = 'Alex';
const age = 25;
const msg = 'My name is ' + name + ' and I am ' + age + ' years old.';
console.log(msg);
// My name is Alex and I am 25 years old.With ES6 (template strings):
const msg = `My name is ${name} and I am ${age} years old.`;
console.log(msg);
// My name is Alex and I am 25 years old.The code becomes cleaner, shorter, and more readable.
2. You can insert any expressions
const a = 5;
const b = 10;
console.log(`a + b = ${a + b}`); // a + b = 15
console.log(`Random number: ${Math.random()}`);
console.log(`Uppercase: ${'js'.toUpperCase()}`);Everything inside ${ ... } is evaluated as a regular JS expression.
3. Multiline strings without \n
Before:
const text = 'Line 1\n' +
'Line 2\n' +
'Line 3';Now:
const text = `
Line 1
Line 2
Line 3
`;
console.log(text);The newline character (\n) is not needed, the format is preserved as is.
4. Interpolation with nested templates
You can combine templates and even use them inside functions:
const name = 'Alex';
const hobby = 'coding';
const greeting = `Hello, ${name}! Your hobby is ${hobby.toUpperCase()}.`;
console.log(greeting);
// Hello, Alex! Your hobby is CODING.5. Tagged templates (advanced use)
Template strings can be "tagged" with functions for custom processing:
function highlight(strings, ...values) {
return strings.reduce(
(result, str, i) => result + str + (values[i] ? `**${values[i]}**` : ''),
''
);
}
const name = 'Alex';
const lang = 'JavaScript';
console.log(highlight`Hello ${name}, you love ${lang}!`);
// Hello **Alex**, you love **JavaScript**!This is used in libraries like styled-components (CSS in React), graphql-tag, and for safe HTML templates.
6. Comparison with regular quotes
| Feature | 'single' / "double" | template |
|---|---|---|
| Variable substitution | No | Via ${} |
| Multiline strings | No (needs \n) | Yes, directly |
| Nested expressions | No | Yes (${x + y}) |
| Tagging (functions) | No | Yes |
| Quote character inside | Needs escaping (\') | Not needed, unless there is a ` |
| ES support | Older versions | Since ES6 (2015) |
Short recap
| What it does | Example | Result |
|---|---|---|
| Variable substitution | Hello, ${name} | "Hello, Alex" |
| Expressions | ${1 + 2} | "3" |
| Multiline strings | A\nB | "A↵B" |
| Tagged templates | tag`text ${x}` | Processed as a function |
A simple rule
Regular quotes are for simple strings. Backticks are for dynamic and multiline strings.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.