Lesson 3 +10 XP

JavaScript Output

JavaScript Output

JavaScript has several ways to display information. There is no single print command, but a few options.

1. innerHTML

document.getElementById("demo").innerHTML = "New text";

This replaces the content of an HTML element. It is the most common way to change a page.

2. document.write()

document.write("Hello");

This writes directly into the HTML output. Only use it for testing, because after a page loads, it erases the whole document.

3. window.alert()

alert("Hello!");

This pops up a dialog box with a message. Use it to give the user a quick message or warning.

4. console.log()

console.log("Debug message");

This writes to the browser console, invisible to users. It is the best tool for debugging. Open the console with F12.

5. window.print()

window.print();

This opens the print dialog so the user can print the page.

TL;DR

  • innerHTML changes page content.
  • document.write() is for testing only.
  • alert() pops up a message box.
  • console.log() is the go-to debugging tool.
  • window.print() opens the print dialog.