JS Output

No displays or built - in print functions are available for JavaScript. That is why we have to use the JavaScript output function.

The data can be "displayed" through several techniques:

  • Writing into the HTML output using document.write().
  • Writing into an HTML element, using innerHTML.
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

 

document.write() function is convenient for testing purposes. It’s primary function is to delete all HTML whenever the HTML document is loaded. We have to be very careful with this JavaScript output method.

Example:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(3 + 4);
</script> </body> </html>

 

Output:

My First Web Page

My first paragraph.

Never call document.write after the document has finished loading. It will overwrite the whole document.

7

Example 2

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(4 + 3)">Try it</button>

</body>
</html>

 

Output:

My First Web Page

My first paragraph.

Note: use the document.write() method only for testing!

Use the document.getElementById(id) method to access an HTML element by its ID

In the example below, We see that HTML element is defined by the id attribute. The HTML content is defined by the innerHTML property and after the button click the element changes:

Example:

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 3 + 4;
</script>

</body>
</html>

 

Output:

 

My First Web Page

My First Paragraph.

7

 

This JavaScript output method displays the given data in an alert-box. A small box with a closing button appears, and it disappears once you have clicked on it. This is an ideal method for short and rapidly - closing informative messages.

Example:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(4 + 3);
</script>

</body>
</html>

 

Output:

My First Web Page

My first paragraph.

 

We should use the console.log() function to display data straight in the console. The JavaScript console.log() function is mainly used for debugging your code as it makes the JavaScript print to console.

Open the browser console with F12 and select "Console"

Example:

<!DOCTYPE html>
<html>
<body>

<script>
console.log(4 + 3);
</script>

</body>
</html>

 

Output: