JavaScript Output


JavaScript does not have any printing or output functions.

JavaScript to Display Data

JavaScript can output data in different ways:

  • Use window.alert() to pop up a warning box.

  • Use the document.write() method to write the content into the HTML document.

  • Use innerHTML to write to HTML elements.

  • Use console.log() to write to the browser's console.


Use window.alert()

You can pop up a warning box to display the 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! 



Work on HTML Elements

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

Please use the "id" attribute to identify the HTML element, and innerHTML to get or insert the 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 has been modified.";
    </script>
</body>
</html>

Try It! 

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

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

innerHTML = "Paragraph has been modified." is the JavaScript code used to modify the HTML content (innerHTML) of the element.


In This Tutorial

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

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


Write to HTML document

For testing purposes, you can write JavaScript directly in the 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! 

Note

Please use document.write() to write only to the document output.

If you execute document.write 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! 


Write to The Console

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

Use F12 in the browser to enable the debug mode, 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>

Example console screenshot:

image.png

 Try It! 


Do you know?

NoteDebugging in the program is the process of testing, finding and reducing bugs.