I'm looking at generating dynamic HTML strings in JavaScript, using either template literals or string concatenation. Template literals are neat, using backticks and allowing interpolation, which makes code readable and maintainable. They also have advantages like avoiding multiple + signs and offering XSS sanitization. However, there's still a risk of injection with innerHTML.
On the other hand, string concatenation has its own pros, like older compatibility and ease of building incrementally, but can be less readable and more error-prone. Overall, both methods have their place!Examining JSON.stringify usage
I'm diving into the purpose of JSON.stringify, which is meant to convert JavaScript values to JSON, not HTML. But I see a few use cases, like embedding data attributes or debugging objects as strings.
However, using it for HTML can be problematic. It escapes quotes in a way that might break HTML, creates issues with special characters, and can make things harder to read. It seems that creating an object representation of HTML and using JSON.stringify isn't the best practice. Instead, I should focus on separate use cases: markup building and data serialization.Providing guidelines for dynamic HTML in JavaScript
When generating dynamic HTML strings in JavaScript, I recommend using template literals for clarity and maintainability. String concatenation can work for simple or performance-critical loops, but only if measured. JSON.stringify is best reserved for embedding or serializing data, not for building markup.
I should also consider alternatives like DOM methods (e.g., document.createElement) or using frameworks and templating libraries to avoid string-level injection issues. Additionally, JSON.stringify tends to be slower on complex objects and introduces escaped sequences. It's essential to differentiate escaping for JSON and HTML, as JSON doesn't sanitize HTML special characters. Readability is another key factor to weigh in decisions.Providing examples for dynamic HTML generation
Here's how I can generate dynamic HTML strings:
Using template literals, I could have something like this:
javascript
const html = `
<ul>
${items.map(item => `<li>${escapeHTML(item.name)}</li>`).join('')}
</ul>
`;
For concatenation, it would look like this:
javascript
let html = '<ul>';
for (const item of items) {
html += '<li>' + escapeHTML(item.name) + '</li>';
}
html += '</ul>';
However, using JSON.stringify for this purpose is a misuse. For example:
That would require a renderer to interpret the JSON and create the DOM. Whichever method I choose, it's crucial to sanitize or avoid innerHTML to prevent XSS issues. Additionally, I can explore tagged template literals, like `html```, for libraries such as lit-html, which support safe and efficient updates. Here’s a comparison focused specifically on generating dynamic HTML strings in JavaScript.
Good tooling: Syntax highlighting in many editors; tag functions (e.g. html from lit-html) can add safety or optimizations.
Modern JS engines optimize them well: Performance is roughly on par with concatenation for typical UI use.
Cons
Still just string-based HTML: If you put this into element.innerHTML, you still have:
XSS risk if you interpolate unsanitized user input.
No type safety or compile-time checks.
For extremely hot inner loops with millions of iterations, you may want to micro-benchmark vs concatenation or DOM APIs, but that’s edge-case.
When to use
Default choice for most dynamic HTML generation in modern JavaScript (browser or Node).
Especially good for larger, structured templates.
2. String concatenation (+, .concat, array.join)
Example
js
const title = 'Hello';
const items = ['one', 'two'];
let html = '<section class="card">';
html += '<h1>' + title + '</h1>';
html += '<ul>';
for (const item of items) {
html += '<li>' + item + '</li>';
}
html += '</ul>';
html += '</section>';
Or using an array:
js
const parts = [];
parts.push('<section class="card">');
parts.push('<h1>', title, '</h1>');
parts.push('<ul>');
for (const item of items) {
parts.push('<li>', item, '</li>');
}
parts.push('</ul></section>');
const html = parts.join('');
Pros
Works in very old environments (pre-ES6).
Incremental building: Occasionally feels more natural when you’re appending in many places inside loops or conditions.
array.join('') pattern can be slightly more predictable for performance in some older engines.
Cons
Low readability for non-trivial templates:
Lots of '...' + var + '...'.
Escaping quotes (' vs ") is error-prone.
Harder to visually parse as HTML.
Easy to miss a +, quote, or closing tag.
Same XSS/security considerations as template literals if you inject into innerHTML.
When to use
Simple, very small snippets (e.g., 'Hello ' + name).
Legacy environments where ES6 template literals are unavailable.
Micro-optimized hot loops only if measured and justified.
For almost any non-trivial HTML, template literals are more maintainable.
3. JSON.stringify for “HTML generation”
JSON.stringify is not an HTML templating tool. Its purpose is:
Convert a JavaScript value to a JSON string suitable for data interchange.
Still, it sometimes shows up in HTML-related code in a few ways:
3.1. Embedding data into HTML (legitimate use)
js
const data = { userId: 123, name: 'Alice "Admin"' };
const html = `
<div id="root" data-props='${JSON.stringify(data)
.replace(/'/g, ''') // avoid breaking the single-quoted attribute
}'></div>
`;
This pattern is common in SSR setups (Next.js, etc.) to hydrate data on the client.
Pros
Correct way to serialize data objects (not HTML) into a string.
JSON is easily parsed back on the client with JSON.parse.
Cons
Must be careful with attribute quoting and escaping.
Still need to consider XSS: JSON escaping is not HTML escaping.
3.2. Using JSON.stringify to “generate HTML”
For example:
js
const card = {
tag: 'section',
class: 'card',
title: 'Hello',
items: ['one', 'two']
};
const html = JSON.stringify(card); // ❌ not actual HTML
Or:
js
const html = `
<pre>${JSON.stringify(user)}</pre> // ❌ usually not what you want
`;
Problems:
Not HTML: You get JSON, not markup ({"tag":"section",...}).
Escaping is for JSON, not HTML:
JSON escapes ", \, control chars.
HTML needs &, <, >, quotes-in-attributes, etc.
If you then inject this into innerHTML:
You’ll see raw JSON text, not a rendered element, unless that’s literally what you intended (a debug dump).
JSON.stringify can be slower and heavier than direct HTML string building:
It walks full object graphs, handles cycles (with error), etc.
When (and only when) to use JSON.stringify with HTML
Embedding data inside HTML to be parsed later by JS (data-* attributes, <script type="application/json">, etc.).
Debugging: showing JSON in a <pre> for inspection.
Not for generating real HTML markup.
4. Security & correctness: template literals vs concatenation vs JSON.stringify
Regardless of which you use:
If you do element.innerHTML = html; and html contains user-controlled data,
you must sanitize or escape the dynamic parts to avoid XSS.
Neither template literals nor concatenation nor JSON.stringify automatically protect you.
Examples:
js
// Unsafe: userName may contain <script> etc.
const html = `<div>${userName}</div>`;
// Safer: escape HTML entities
function escapeHTML(str) {
return str.replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>',
'"': '"', "'": '''
}[c]));
}
const htmlSafe = `<div>${escapeHTML(userName)}</div>`;
For more robust safety and performance, consider:
DOM APIs (createElement, textContent, appendChild) instead of innerHTML.
Templating libraries/frameworks (React, Vue, lit-html, etc.) that handle escaping and updates.
5. Performance overview
In modern engines:
Template literals vs concatenation:
Performance is usually very similar.
For typical UI use (rendering lists, cards, forms), the difference is negligible.
Choose based on readability, not performance.
JSON.stringify:
Generally slower for generating HTML-like output because:
It walks your whole object and performs JSON-specific escaping.
Then you still need to turn JSON into HTML (second step) if HTML is the goal.
It’s for data serialization, not templating.
6. Quick summary
Template literals (``)
Best for: Generating dynamic HTML strings in modern JS.
Strengths: Readable, maintainable, expressive.
Use for: Most dynamic HTML templating.
String concatenation (+, join)
Best for: Tiny snippets, legacy environments, or validated micro-optimizations.
Strengths: Universal support, explicit control.
Weaknesses: Ugly and error-prone for non-trivial markup.
JSON.stringify
Best for: Serializing data, often embedded into HTML for client-side parsing.
Strengths: Correct JSON output, interoperable.
Weaknesses: Not HTML; wrong escaping for markup; slower; confusing if misused.
If your goal is “dynamic HTML string to insert into the DOM,” use template literals (with proper escaping or a safe templating layer), not JSON.stringify.