JavaScript Output
JavaScript can display data in different ways. Here are the four most common methods.
| Method | Where Output Goes |
|---|---|
| innerHTML | Into an HTML element |
| document.write() | Directly into the page (testing only) |
| window.alert() | Browser pop-up alert box |
| console.log() | Browser developer console |
| window.print() | Sends page to printer |
Using innerHTML
The most common way to display data in HTML. Access an element by id and set its innerHTML property.
innerHTML Example
let result = 5 + 6;
console.log("5 + 6 =", result);
// In a browser: document.getElementById("demo").innerHTML = result;Using console.log()
console.log() is mostly used for debugging. Open the browser developer tools (F12) to see console output.
console.log() Examples
console.log("Hello from console.log!");
console.log(5 + 6);
console.log([1, 2, 3]);
console.log({ name: "Alice", age: 30 });Using window.alert()
alert() Example
// alert() shows a popup — window prefix is optional
// window.alert(5 + 6);
// alert(5 + 6);
console.log("alert() would show a browser popup with: " + (5 + 6));Using document.write()
document.write() is useful for testing only. If used after the page loads it will delete all existing HTML.
document.write() Danger
// Only safe to use during page loading (testing)
// document.write(5 + 6);
console.log("document.write() would output:", 5 + 6);📝 Note: Never use document.write() in a live production site — it overwrites the entire page content when called after load.
Exercise:
Which method is used to write to the browser's developer console?