JavaScript Output

JavaScript can display information to users and developers in several different ways, each suited to a different purpose.

Ways to Produce Output

JavaScript does not have a single built-in print command. Instead, it offers a handful of techniques for showing data, and the right choice depends on where you want the result to appear: inside the page, in a pop-up dialog, or in the developer console. Learning what each option is good for will save you a lot of confusion early on.

  • Write directly into an HTML element by changing its innerHTML.
  • Write straight into the document stream using document.write().
  • Show a blocking pop-up message with window.alert().
  • Log values to the browser console with console.log() for debugging.

Writing Into an HTML Element

The most common way to show output on a real web page is to select an element and update its innerHTML property. You first grab a reference to the element (for example by its id), then assign a new string of HTML or text to it. This is the approach you will use in almost every practical project.

Example

<!DOCTYPE html>
<html>
<body>

<h2>Writing Into an HTML Element</h2>
<p id="result"></p>

<script>
document.getElementById("result").innerHTML = "Hello, world!";

// You can also insert computed values
const total = 12 + 8;
document.getElementById("result").innerHTML = "The total is " + total;
</script>

</body>
</html>

Using document.write() and alert()

document.write() is handy for quick tests because it dumps content directly onto the page. Be careful, though: calling it after the page has finished loading will erase all existing content. window.alert() opens a small dialog box that interrupts the user until they click OK, which makes it useful for warnings but disruptive for everyday output.

Example

<!DOCTYPE html>
<html>
<body>

<h2>Using document.write() and alert()</h2>

<script>
// Quick test output during development
document.write("This appears in the page body.");

// A blocking pop-up dialog
window.alert("Your changes have been saved.");
</script>

</body>
</html>
Note: Reach for console.log() while you are building and debugging. It never disturbs the user, accepts multiple values at once, and keeps a clean history of what your code is doing.
MethodWhere it showsBest for
innerHTMLInside a chosen HTML elementReal page output
document.write()Directly in the documentQuick throwaway tests
window.alert()Pop-up dialog boxUrgent messages
console.log()Browser developer consoleDebugging

Exercise: JavaScript Output

Which method writes output to the browser's developer console?