How to display JavaScript variable value in HTML page

Last updated:4th Nov 2021

This tutorial will show you how to display javascript variables inside the HTML page in three different ways.

  • By using document.write() method
  • By using innerHTML property 
  • By using window.alert()  method

display variable using document.write() method

document.write() method will replace all content inside HTML body tag with output of document.write().

you can display javascript variables in this method. for example

<html>
<body>
   <script>
	    var x = 10;
	    document.write("value of x="+x);
   </script>
</body>
</html>
output will be 10

Display javascript variable using innerHTML property

you can display javascript variable value in any place of HTML file by using innerHTML property
for example

<!DOCTYPE html>
<html>
<body>
  <h3>value of javascript variable are <span id="demo"></span></h3>
   <script>
	 var a=5+10
	 document.getElementById("demo").innerHTML=a;
   </script>
</body>
</html> 
Run now
value of javascript variable are 15

Display javascript variable using window.alert() method

alert() method will display value in dialog box for example

<!DOCTYPE html>
<html>
<body>
   <script>
	 var a=5+10;
	 alert(a);
   </script>
</body>
</html> 
Run now