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:

Free Exclusive Traffic Tips

Enter your email below to get access to my
proven SEO and traffic tips.

Hello, I am Dharmendra Yadav and I am a Blogger, Web Developer, Web Designer, Search Engine Optimizer, Digital Marketing Instructor. You can find me on Facebook , Linkedin

Leave a Comment