How to Display Output in JavaScript

There are numerous scenarios where you’d need to display output data (from variables, functions, etc.), particularly when trying to debug a feature or understand why your code doesn’t work.

There are several ways to generate outputs using JavaScript, such as writing output to a browser window or console, displaying output in a dialog box, creating output in an HTML element, and so on.

This article covers the following ways JavaScript can display (output) data:

  • Write to an HTML element using innerHTML.
  • Write to the browser console using console.log().
  • Use window.alert() to write to an alert box.
  • Use document.write() to write HTML output.

Using innerHTML

The document.getElementById() method in JavaScript can be used to query and replace specific HTML elements with either static or dynamic data. This also works for all other JavaScript selectors in the document family.

<div class="container">
<p id="replace-me"></p>
</div>
document.getElementById("replace-me").innerHTML = "innerHTML Output";

Writing Output to Browser Console

Using the console.log() method, you can quickly generate messages or write data to the browser console. This is a basic but effective way to produce verbose output.

console.log(1 + 2);  // 3

Displaying Output in an Alert Box

You can also use alert dialogs to display messages to the user or output data. The alert() method generates an alert dialog.

window.alert("Output");

Using document.write()

The document.write() method removes all content from an HTML document and replaces it with new data.

document.write("new data");

When you use the document.write() method after the page loads; it will overwrite any existing content in the document. Consider the following example:

<h2>Heading</h2>
<p>Body Content</p>

<button type="button" onclick="document.write('New Body Content!')">Click me!</button>

The document.write() method is typically reserved for testing purposes only.