JavaScript Output

There are certain situations in which you may need to generate output from your JavaScript code. For example, you might want to see the value of variable, or write a message to browser console to help you debug an issue in your running JavaScript code, and so on.

JavaScript Display Possibilities

JavaScript can “display” data in different ways:

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

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:

Example: This example uses innerHTML to display the data.

Output:

Using document.write()

For testing purposes, it is convenient to use document.write():

Example: This example uses document.write() property to display data.

Output:

If you use the document.write() method method after the page has been loaded, it will overwrite all the existing content in that document. Check out the following example:

Using window.alert()

It displays the content using an alert box.

Syntax: 

Output:

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

Example: This example uses console.log() property to display data.

Output:

Share on:

Hello, I am Dharmendra Yadav and I am a Python Developer with experience in web development using Django, Flask, REST API, SQL, MySQL, HTML, CSS, JavaScript, WordPress, Oracle Cloud, AWS and Git. I also write technical articles where I explain web development and Software Engineering. Facebook , Linkedin

Leave a Comment