How to Print Output in JavaScript: Simple Guide
To print output in JavaScript, use
console.log() to show messages in the browser console or terminal. You can also use alert() to show popup messages or document.write() to write directly to the webpage.Syntax
The most common way to print output in JavaScript is using console.log(). It takes one or more values inside parentheses and prints them to the console.
Other methods include alert() which shows a popup message, and document.write() which writes directly to the webpage.
javascript
console.log(value1, value2, ...); alert(message); document.write(content);
Example
This example shows how to print text and numbers using console.log(), display a popup with alert(), and write text on the webpage with document.write().
javascript
console.log('Hello, world!'); console.log('Sum:', 5 + 3); alert('This is a popup message!'); document.write('This text is written on the webpage.');
Output
Hello, world!
Sum: 8
(This shows a popup with message)
(This writes text on the webpage)
Common Pitfalls
One common mistake is forgetting to open the browser console to see console.log() output. Another is using document.write() after the page loads, which can overwrite the whole page.
Also, alert() stops the page until you click OK, so use it sparingly.
javascript
/* Wrong: document.write after page load */ window.onload = function() { document.write('This will erase the page content!'); }; /* Right: Use console.log instead */ window.onload = function() { console.log('Page loaded'); };
Quick Reference
| Method | Description | Where Output Appears |
|---|---|---|
| console.log() | Prints messages to the browser console or terminal | Browser Console / Terminal |
| alert() | Shows a popup alert box with a message | Popup dialog on webpage |
| document.write() | Writes text directly into the webpage HTML | Webpage content area |
Key Takeaways
Use console.log() to print messages to the browser console for debugging.
alert() shows popup messages but pauses page interaction until dismissed.
Avoid using document.write() after the page loads to prevent overwriting content.
Open the browser console (F12 or Ctrl+Shift+I) to see console.log output.
Choose the output method based on whether you want console, popup, or page display.