HtmlCssMonk

Types of OUTPUT in JavaScript | Learn basic JavaScript

blogging, blogger, office

DESCRIPTION

JavaScript can “display” our data in different ways:

  • innerHTML – To write into an HTML element.
  • document.write() – To write into HTML output.
  • window.alert() – To write into alert box.
  • console.log() – To write into browser console.

Now , We will go through every type of output one by one.

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content.

Let’s understand better with an Example –

<!DOCTYPE html>
<html>
<body>

<h1>HtmlCssMonk</h1>
<p>Learn Like a Monk</p>

<p id="monk"></p>

<script>
document.getElementById("monk").innerHTML = 8+12;
</script>

</body>
</html>

This Code will produce the following result on your webpage –

Changing the innerHTML property of an HTML element is a common way to display data in HTML.


Using document.write()

document.write() is convenient to use for testing purposes.

Here is an Example –

<!DOCTYPE html>
<html>

<body>

  <h1>HtmlCssMonk</h1>
  <p>Learn Like a Monk</p>

  <script>
    document.write(4+24);
  </script>

</body>

</html>

This Code will produce the following result on your webpage –

Using document.write() after an HTML document is loaded, will delete all existing HTML:


Using window.alert()

We can also display data in alert box using window.alert() . window keyword is optional as it’s a global scope object.

Let’s try an Example –

<!DOCTYPE html>
<html>

<body>

  <h1>HtmlCssMonk</h1>
  <p>Learn like a Monk</p>

  <script>
    window.alert(5 + 6);
  </script>

</body>

</html>

This Code will produce the following result on your webpage –

window.alert(2+2) and alert(2+2) both will produce same result as window is optional.


Using console.log()

We can call the console.log() method in the browser to display data for Debugging purpose.

Here is an Example –

<!DOCTYPE html>
<html>

<body>

  <script>
    console.log(15 + 24);
  </script>

</body>

</html>

This Code will produce the following result on your webpage –


Next topic – Operators in JS

Previous topic – Basics of JS


Leave a Comment

Your email address will not be published. Required fields are marked *