JS Interview Question: When would you use document.write()?

When document.write() is executed after page load, it replaces the entire header and body tag with the given parameter value in string. An invocation could look like this:

document.write(‘<h1>hello world</h1>’);

When working with web application, it is uncommon task to overwrite an entire page, hence why using document.write() is bad practice. It cannot inject string text into a given node point unlike jQuery library selectors and native JavaScript methods. Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document

Another reason not to use document.write() is it doesn’t support XHTML, but its not an issue since most web development uses HTML. Since document.write() fires after a page has finish loading, it causes performance issues and sometimes, may not even fire at all.

The only seem appropriate usage for document.write() is when working third parties like Google Analytics and such for including their scripts. This is because document.write() is mostly available in any browser. Since third party companies have no control over the user’s browser dependencies (ex. jQuery), document.write() can be used as a fallback or a default method.


If you are looking for a platform to develop your clients’ website, check out my SAAS platform https://ecompurpl.com

EcomPurpl.com is the all-in-one solution for anyone looking to create a website. Templates, E-Commerce, Hosting, Galleries, Booking & Appointments, CRM, 24/7 support, and integration of your app are all included.




Software Engineer / Front-End Dev. Currently resides in Las Vegas. https://ecompurpl.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Started with Chrome Extensions

Getting started with chrome extension

The Start of Great Gatsby.js

How to Work with Input Fields in Cypress

Part 1: Building a Progressive Web Application (PWA) with Angular Material and AWS Amplify.

React: What is ‘this’ and why am I getting this Error?

Declarative Charting Library

The Great Gatsby(JS)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
RLyn Ben

RLyn Ben

Software Engineer / Front-End Dev. Currently resides in Las Vegas. https://ecompurpl.com

More from Medium

Learn JavaScript Testing

JavaScript Design Patterns #2: Open-Closed Principle

An example code snippet written in Javascript keeping the open-closed principle in mind.

JavaScript syntax for CRUD operations

Storage API in Javascript