JavaScript Output
JavaScript can show results in four main ways.
| Method | Where the result appears |
|---|---|
innerHTML | Inside an HTML element on the page |
document.write() | Written straight into the page while it loads |
alert() | In a small pop-up box |
console.log() | In the browser's developer console |
Using innerHTML
This is the method you will use most. Find an element with document.getElementById(), then set its innerHTML.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Shop Bill</h2>
<p id="total"></p>
<script>
let tea = 80;
let samosa = 40;
document.getElementById("total").innerHTML = "Total: Rs " + (tea + samosa * 2);
</script>
</body>
</html>Try it Yourself »Total: Rs 160
If you only want plain text, you can use textContent instead. It does not read HTML tags, which makes it safer for text typed by users.
Using document.write()
document.write() writes into the page while it is loading. It is fine for quick tests.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Quick Test</h2>
<script>
document.write(5 + 6);
</script>
</body>
</html>Try it Yourself »11
Never call document.write() after the page has finished loading, for example from a button click. It clears the whole page and replaces it with the new text.
Using alert()
alert() opens a small pop-up. The user must click OK to close it.
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('Your form was submitted!')">Submit</button>
</body>
</html>Try it Yourself »Alerts are annoying if used too much, so real websites rarely use them.
Using console.log()
console.log() writes to the browser console. Visitors do not see it, but developers use it all the time to check values while fixing bugs. Open the console with F12 (or right click, then Inspect, then the Console tab).
Example
let student = "Ayesha";
let marks = 87;
console.log(student, "scored", marks);Ayesha scored 87
Printing the Page
JavaScript has no print command for text, but window.print() opens the browser's print dialog for the current page.
Example
<!DOCTYPE html>
<html>
<body>
<p>Fee receipt for Ali Khan</p>
<button onclick="window.print()">Print receipt</button>
</body>
</html>Try it Yourself »Exercise
Exercise
Which method shows a value in the browser console, where only developers see it?
