JavaScript Output
JavaScript can show output in four ways.
| Method | Where the output goes |
|---|---|
console.log() | The browser console. Best for testing |
alert() | A pop-up box |
element.innerHTML / textContent | Inside an HTML element on the page |
document.write() | Directly into the page while loading. Avoid it |
console.log()
let name = "Robin";
console.log("Hello " + name);
console.log(5 + 3);
Output of the above program is
Hello Robin
8
Writing into an HTML element
First find the element with getElementById(), then change its textContent (plain text) or innerHTML (can contain HTML tags).
<p id="demo">Old text</p>
<script>
document.getElementById("demo").textContent = "New text from JavaScript";
</script>
Result on the page
New text from JavaScript
Note:
Use textContent when you show text typed by a visitor. innerHTML can run harmful HTML or scripts if the text comes from a user (XSS attack).
alert()
alert("Welcome to the site!");
Why avoid document.write()?
document.write() after the page has loaded deletes the whole page and replaces it with the new text. It is only seen in very old code.
Summary
- Use
console.log()to test your code. - Use
textContentto show text in an element. - Avoid
document.write(). - Next: JavaScript Syntax.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |