3 Ways to Print a Variable in JavaScript

JavaScript is used to enhance the user experience on the website by adding user interactivity. You surely need to print a value of a variable in JavaScript to an HTML web page. This post will teach you 3 ways to print a variable in JavaScript.

How to Print a Variable on HTML Page with innerHTML

You can use innerHTML in JavaScript to print a variable on the screen. You first need to refer to a DOM node where you want to display the value. The following example prints the variable in a heading element with innerHTML.

Please read more about the innerHTML on mozzila documentation.

Using innerText to Print a Variable in JavaScript

You can also use innerText in JavaScript to print a variable value on an HTML web page. The innerText is similar to innerHTML in use but it actually just changes the text inside the tag. The following code snippet use innterText to change the text content of the header.

Here is more details about the innerText on mozzila documentation.

How to Print a Variable Using console.log

The console.log function is very helpful in debugging. You can use it to print a variable value on the console. To see the output of  console.log you need to go to developer options > console in the browser. Here is a simple example of printing the variable with console.log

Conclusion

There are a couple of ways to print the value of a variable in JavaScript. You can use console.log if you are just debugging the code. The innerHTML and innerText is used to print the variable in an HTML web page.

 

Latest articles

Related articles