JavaScript Output


JavaScript does not have any print or output functions.

JavaScript Display Data

JavaScript can output data in different ways:

  • Usingwindow.alert()pop up an alert box.
  • Usingdocument.write()method writes content to an HTML document.
  • UsinginnerHTMLwrite to an HTML element.
  • Usingconsole.log()write to the browser console.

Using window.alert()

You can pop up an alert box to display data:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Page</h1>
<p>My first paragraph.</p>

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

</body>
</html>

Try it Yourself »

Manipulate HTML Elements

To access an HTML element from JavaScript, you can use document.getElementById(id) method.

Use the "id" attribute to identify the HTML element, and innerHTML to get or insert element content:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My first paragraph</p>

<script>
document.getElementById("demo").innerHTML = "Paragraph modified.";
</script>

</body>
</html>

Try it Yourself »

The above JavaScript statement (inside the <script> tag) can be executed in a web browser:

document.getElementById("demo")is JavaScript code that uses the id attribute to find an HTML element.

innerHTML = "Paragraph modified."is JavaScript code used to modify the element's HTML content (innerHTML).


In this tutorial

In most cases, in this tutorial, we will use the method described above to output:

The example above directly writes the <p> element with id="demo" to the HTML document output:


Write to an HTML document

For testing purposes, you can write JavaScript directly into an HTML document:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My first paragraph.</p>

<script>
document.write(Date());
</script>

</body>
</html>

Try it Yourself »

Note

Using document.write() you can write content to the document.

If document.write is executed after the document has finished loading, the entire HTML page will be overwritten.


Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p>My first paragraph.</p>

<button onclick="myFunction()">Click me</button>

<script>
function myFunction() {
    document.write(Date());
}
</script>

</body>
</html>

Try it Yourself »


Write to console

If your browser supports debugging, you can use theconsole.log()method to display JavaScript values in the browser.

In the browser, use F12 to enable debugging mode, and click the "Console" menu in the debug window.

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html>

Try it Yourself »

Example console screenshot:


Did you know?

Note Debugging in programming is the process of testing, finding, and reducing bugs (errors).
Other extensions