How to display data using JavaScript

Introduction

JavaScript has a variety of APIs that are used to display data to the DOM. Some of these APIs display data directly on the page, while others give pop-up alerts on the page or print to the browser console.

In this shot, we are going to look into these APIs and explain how they work.

How is data displayed?

In JavaScript, data is displayed via:

  • window.alert()
  • window.promt()
  • document.write()
  • innerHtml
  • console.log()

window.alert()

An alert is a pop that displays information on the screen. We use the alert() API to display an alert on the screen.

Example

  • JavaScript
  • Output
An example of the "window.alert()" API

The code shown above leads to a pop-up alert with a message that says “Welcome to My Website” on the screen.

window.prompt()

The prompt() API is similar to the alert() API, except that it requires an input.

Example

  • JavaScript
  • Output
An example of the "window.prompt()" API

The code shown above asks for a name input with the prompt() API that we set up in line 1. Then, it takes the name we input in order to display it as an alert that we set up in line 2.

document.write()

The document.write() API prints or writes directly on the page.

Example

  • JavaScript
  • Output
An example of the "document.write()" API

innerHTML

The innerHTML API is used to change the content of an element in the DOM. It is commonly used with the document.getElementById('id') API to get an element and then change it.

Example

  • HTML
  • JavaScript
  • Output
An example of the "innerHTML" API

Line 5 of the HTML section is a paragraph with an id and content.

In line 1 of the JavaScript section, the content was changed using the innerHtml API.

Look closely at how it was used for best practice.

console.log()

The console.log() API prints whatever is inside the bracket to the browser console.

Example

Console
An example of the "console.log()" API

The code written above shows all the ways to display data in JavaScript. We may practice these to gain a better understanding of how data can be displayed using different APIs in JavaScript.

Free Resources