Today, you will learn how to generate outputs in JavaScript.
Certain situations may warrant you to generate output from your JavaScript code. For instance, you may want to see the value of the variable, or write a message to the browser console or browser window to assist you to debug an issue in your running JavaScript code, and so on.
Writing output to the browser console or browser window, displaying output in alert dialog boxes, and writing output into an HTML element are some of the many different ways we can use to generate output in JavaScript. We will throw more light on each of these in the following sections.
This method is very simple, yet powerful in generating well-detailed output. You can use the console.log() method to easily output a message or write data to the browser console. Here's an example:
Example :
// Printing a simple text message
console.log("Hello World!"); // Prints: Hello World!
// Printing a variable value
var x = 10;
var y = 20;
var sum = x + y;
console.log(sum); // Prints: 30
Tip: To get unrestricted access to your web browser's console, first press the F12 key on the keyboard to open the developer tools then click on the console tab.
To generate output in JavaScript you can as well use alert dialog boxes to display the message or output data to the user. The Alert() method is used to create an alert dialog box. Here is an example:
// Displaying a simple text message
alert("Hello World!"); // Outputs: Hello World!
// Displaying a variable value
var x = 10;
var y = 20;
var sum = x + y;
alert(sum); // Outputs: 30
The document. write() method can only be used to write the content to the current document if that document is parsed. Here's an example:
Example :
// 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
The document.write() method will overwrite all the existing content in that document after the page has been loaded. Check out the following example:
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
<button type="button" onclick="document.write('Hello World!')">Click Me</button>
To write or insert output inside an HTML element using the element's innerHTML property. However, ensure you select the element first using a method such as getElementById() before writing the output as demonstrated in the following example:
<p id="greet"></p>
<p id="result"></p>
<script>
// Writing text string inside an element
document.getElementById("greet").innerHTML = "Hello World!";
// Writing a variable value inside an element
var x = 10;
var y = 20;
var sum = x + y;
document.getElementById("result").innerHTML = sum;
</script>
You will learn about manipulating HTML elements in detail in the JavaScript DOM manipulation chapter.