Javascript

JavaScript Output

JavaScript can display data in different ways. 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 a variable, test your code, get input from the user and so on.

JavaScript Display Possibilities

Using:

  •  innerHTML.
  • document.write().
  • window.alert().
  • 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.
As demonstrated in the following example:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First JS </h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

You will learn about manipulating HTML elements in detail in the Javascript DOM Manipulation chapter.


Using document.write()

You can use the document.write() method to write the content to the current document only while that document is being parsed. 

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Writing into a Browser Window with JavaScript</title>
</head>
<body>

    <script>
    // Printing a simple text message
    document.write("Hello World!"); // Prints: Hello World!
    
    // Printing a variable value 
    var x = 10;
    var y = 20;
    var sum = x + y;
    document.write(sum); // Prints: 30
    </script>

</body>
</html>                            

The  document.write() method should be used only for testing purposes.


Using window.alert()

You can also use an alert box to display data

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>
<body>

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

</body>
</html> 

Using console.log()

For debugging or testing purposes, you can use the console.log() method to display data to the browser console.

Example

// Printing a simple text message
console.log(" Hey there! "); // Prints: Hey there!

// Printing a variable value 
var x = 5;
var y = 5;
var sum = x + y;
console.log(sum); // Prints: 10