Skip to content

JavaScript print variable | Example code

  • by

JavaScript does not have any print object or print methods compared to other programming languages. You can use JavaScript innerHTML, document.write(), window.alert() and console.log() to print (display) variable in different ways.

JavaScript print variable

Simple example code.

Using innerHTML

Use the document.getElementById(id) method to access an HTML element, and innerHTML property defines the HTML content.

<!DOCTYPE html>
 <html>
 <body>

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

    <script>
      var res = "Print varible";
      document.getElementById("demo").innerHTML = res;
    </script>

</body>
</html> 

Output:

JavaScript print variable

Using document.write()

Using document.write() after an HTML document is loaded, will delete all existing HTML:

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

Using window.alert()

You can skip the window keyword. Alert box to display data:

<script>
window.alert(500;
</script>

Using console.log()

Mostly it is used for debugging purposes.

<script>
console.log('Hello');
</script>

JavaScript Print

You can call the window.print() method in the browser to print the content of the current window.

 <!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html> 

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *