Why is document.write() considered bad practice?

JavaScript

The short answer

document.write() inserts content directly into the HTML document. If called after the page has finished loading, it erases the entire page and replaces it with the new content. It blocks HTML parsing, hurts performance, and does not work with modern asynchronous scripts. There is almost never a good reason to use it today.

What it does

// During page load — inserts into the document
document.write('<h1>Hello</h1>');
// After page load — erases everything and replaces it
window.addEventListener('load', () => {
document.write('<h1>Hello</h1>'); // entire page is gone
});

Why it is bad

1. Erases the page if called late — If you call it after the document has finished parsing, it calls document.open() first, which wipes out all existing content.

2. Blocks parsing — The browser has to pause HTML parsing while document.write() executes. This makes page loading slower.

3. Does not work with async/defer scripts — If a script loaded with async or defer uses document.write(), the browser ignores it because the document might already be closed.

4. Hard to maintain — It mixes content generation with page structure in a way that is difficult to debug and reason about.

What to use instead

// Insert HTML
element.innerHTML = '<h1>Hello</h1>';
// Insert text (safer)
element.textContent = 'Hello';
// Create and append elements
const h1 = document.createElement('h1');
h1.textContent = 'Hello';
document.body.appendChild(h1);

Interview Tip

This is a quick knowledge question. Explain the two main problems: it erases the page if called after load, and it blocks parsing. Then mention the modern alternatives (innerHTML, createElement). Keep it short.

Why interviewers ask this

This tests basic DOM knowledge. Interviewers want to see if you know why certain old APIs are problematic and what modern alternatives exist.