You might have seen threads where developers debate whether to use string concatenation or template literals for building UI strings, URLs, and logs. If you are juggling variables, function outputs, and formatting in the same string, understanding interpolation can boost readability and reduce bugs.
Hi all,
I keep seeing template literals in code reviews and want to make sure I am using them correctly. What is string interpolation in JavaScript? How do I use it with template literals for variables, expressions, multiline strings, and conditional output? Are there pitfalls I should avoid, especially around security when inserting user input into the DOM?
String interpolation is the process of inserting the result of expressions directly into a string. In JavaScript, the modern way to do this is with template literals, which use backticks and the ${...} placeholder. Let’s dive a little deeper:
const name = 'Ari';
const total = 19.99;
const message = `Hi ${name}, your total is $${total.toFixed(2)}.`;
console.log(message); // "Hi Ari, your total is $19.99."Code language: JavaScript (javascript)
- Use backticks:
`...` - Embed any JS expression in
${...} - Supports multiline strings without
\n
const list = ['apples', 'oranges', 'pears'];
const summary = `You bought:
- ${list.join('\n- ')}
Thanks!`;
console.log(summary);Code language: JavaScript (javascript)
const qty = 3;
const unit = 4.5;
const isMember = true;
const line = `Subtotal: $${qty * unit} ${isMember ? '(member discount applies)' : ''}`;
console.log(line);Code language: JavaScript (javascript)
- Forgetting backticks. Single or double quotes do not interpolate.
- Inserting unsanitized user input into HTML. String interpolation in JavaScript does not auto-escape, so always keep safety in mind.
- Getting
undefinedornullin output. Use default values, such as${val ?? 'N/A'}.
const literal = `Use backticks \` and placeholders like \${value}.`;
Tagged templates let you post-process interpolated values, useful for formatting or escaping HTML.
function escapeHTML(strings, ...values) {
const esc = v => String(v)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
return strings.reduce((out, str, i) => out + str + (i < values.length ? esc(values[i]) : ''), '');
}
const userInput = '<script>alert(1)</script>';
const html = escapeHTML`<div class="note">${userInput}</div>`;
console.log(html);Code language: PHP (php)
- Building query strings:
const params = new URLSearchParams({ q: 'cats', page: 2 });
const url = <code>/search?${params}</code>;Code language: JavaScript (javascript)
- Formatting numbers and dates:
const price = 39.5;
const formatted = `Total: ${new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price)}`;Code language: JavaScript (javascript)
Interpolation is great for composing delivery URLs and markup. If your app constructs image links, it helps to know how an image URL is structured and how HTML images are embedded. See this guide to the HTML image tag for attributes and best practices.
// Example: Building a responsive <img> with a dynamic srcset
const publicId = 'samples/landscapes/beach';
const widths = [480, 768, 1080];
const srcset = widths.map(w =>
`https://res.cloudinary.com/demo/image/upload/w_${w},c_fill/${publicId}.jpg ${w}w`
).join(', ');
const imgHTML = `
<img
src="https://res.cloudinary.com/demo/image/upload/w_768,c_fill/${publicId}.jpg"
srcset="${srcset}"
sizes="(max-width: 768px) 90vw, 768px"
alt="Beach"
/>`;Code language: JavaScript (javascript)
After you grasp interpolation, you can pair it with Cloudinary to generate dynamic, performant media URLs on the fly.
- Simple template literal URL:
const w = 600, h = 400;
const publicId = 'samples/animals/kitten';
const cldUrl = <code>https://res.cloudinary.com/demo/image/upload/w_${w},h_${h},c_fill,q_auto,f_auto/${publicId}.jpg</code>;
// Use cldUrl in or CSSCode language: JavaScript (javascript)
- Using the JavaScript SDK:
import { Cloudinary } from '@cloudinary/url-gen';
import { fill } from '@cloudinary/url-gen/actions/resize';
const cld = new Cloudinary({ cloud: { cloudName: 'demo' } });
const w = 800, h = 450, publicId = 'samples/poi/bridge';
const img = cld.image(publicId)
.format('auto')
.quality('auto')
.resize(fill().width(w).height(h));
const optimizedUrl = img.toURL();Code language: JavaScript (javascript)
You can also explore helpful utilities in the Cloudinary tools collection.
- Interpolation itself is safe, but inserting untrusted values into HTML is not. Escape or sanitize before injecting into the DOM.
- Prefer setting text content programmatically or using trusted template engines that auto-escape by default.
- String interpolation in JavaScript uses template literals with
${...}to embed expressions in strings. - It supports multiline strings, conditionals, and function calls, and it improves readability over concatenation.
- Escape or sanitize user input before injecting into HTML. Tagged templates can help.
- Combine interpolation with dynamic media URLs and delivery. See image URL structures and HTML image tag best practices for robust output.
Ready to build faster, more dynamic experiences with smart media delivery and transformation? Sign up for a free Cloudinary account and start optimizing your assets today.