Template Literals
Template literals (introduced in ES6) are a powerful way to work with strings in JavaScript. They use backticks (`) instead of single or double quotes and provide features like:
- Multi‑line strings – no need for
\nor concatenation. - String interpolation – embed expressions using
${...}. - Tagged templates – custom processing of template literals.
They are widely used in React for dynamic content, styling with CSS‑in‑JS, and building readable HTML strings.
Instead of quotes, use backticks:
// Old way – single quotes or double quotes
const greeting = 'Hello, world!';
const another = "Hello, world!";
// Template literal
const greeting = `Hello, world!`;
The content inside backticks is a string, but it behaves specially when you include placeholders or newlines.
Note: Template literals are not just strings – they are a language feature that can evaluate expressions and even process them through functions (tagged templates).
With template literals, you can write strings that span multiple lines without concatenation or escape sequences:
// Old way – using \n and concatenation
const message = 'This is line 1\n' +
'This is line 2\n' +
'This is line 3';
// Template literal – clean and readable
const message = `This is line 1
This is line 2
This is line 3`;
This is especially useful for HTML templates inside your JavaScript code.
React Example
In React, you might use template literals to build className strings or inline styles:
const className = `button ${isActive ? 'active' : ''}`;
return <div className={className}>Click me</div>;
The most common use of template literals is embedding expressions using ${expression}. The expression is evaluated, converted to a string (if needed), and inserted into the template.
const name = 'Alice';
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);
// Output: Hello, my name is Alice and I am 30 years old.
// You can also embed any valid JavaScript expression
const total = 10;
const tax = 0.08;
const price = `Total: $${total * (1 + tax)}`;
console.log(price); // Total: $10.8
Important: The expression inside ${} is evaluated in the current scope, so you can use variables, function calls, arithmetic, ternaries, etc.
Tagged templates allow you to parse template literals with a function. The function receives the literal parts (as an array) and the evaluated expressions as arguments. This is used in libraries like styled‑components and graphql‑tag.
function tag(strings, ...values) {
console.log(strings); // array of string parts
console.log(values); // evaluated expressions
// You can return any processed value
return strings.reduce((acc, str, i) => acc + str + (values[i] || ''), '');
}
const name = 'Bob';
const age = 25;
const result = tag`Hello ${name}, you are ${age} years old.`;
console.log(result); // "Hello Bob, you are 25 years old."
A more practical example – a simple CSS‑in‑JS helper:
function css(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i] || ''), '');
}
const color = 'red';
const fontSize = '20px';
const styles = css`
.button {
color: ${color};
font-size: ${fontSize};
}
`;
console.log(styles);
// Output: .button { color: red; font-size: 20px; }
Template literals shine in React for:
- Dynamic class names – combining classes conditionally.
- Inline styles – building style objects (though not directly as strings, you can use template literals for CSS‑in‑JS libraries like
styled‑components). - Building HTML strings – for dangerouslySetInnerHTML.
- Creating URLs – with query parameters.
- Formatting messages – with translations.
// Dynamic class name
const isActive = true;
const buttonClass = `btn ${isActive ? 'btn-active' : 'btn-inactive'}`;
// Building a URL
const userId = 42;
const apiUrl = `https://api.example.com/users/${userId}?include=profile`;
// In a React component
function Greeting({ firstName, lastName }) {
return <h1>Hello, {`${firstName} ${lastName}`}!</h1>;
}
- Template literals use backticks (
`). - They support multi‑line strings without escape sequences.
- String interpolation with
${}allows embedding any expression. - Tagged templates provide powerful custom processing of template literals.
- In React, they are essential for dynamic strings, class names, and CSS‑in‑JS.
Key Takeaway
"Template literals make string handling in JavaScript more expressive and less error‑prone – use them everywhere!"
Happy coding!