JS Generating Output

Generating Output in JavaScript

There are times when you may need to produce output from your JavaScript code. For instance, you might wish to view a variable's value or write a message to the browser console to aid in debugging your JavaScript code as it runs.

JavaScript offers various methods for generating output, such as writing to the browser window or console, displaying in dialog boxes, or writing into an HTML element. We'll explore each methods in detail in the following sections.

Writing Output to Browser Console

You can easily output a message or write data to the browser console using the console.log() method. This method is straightforward yet highly effective for generating detailed output. Here's an 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 access your web browser's console, simply press the F12 key on your keyboard to open the developer tools, and then click on the console tab. It resembles the screenshot here.


Displaying Output in Alert Dialog Boxes

You can also utilize alert dialog boxes to show messages or output data to the user. An alert dialog box is generated using the alert() method. Here's 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

Writing Output to the Browser Window

You can utilize the document.write() method to write content to the current document, but note that this method only works while the document is being parsed. Here's an 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

If you employ the document.write() method after the page has finished loading, it will overwrite all existing content in the document. Take a look at 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>

Inserting Output Inside an HTML Element

You can also write or insert output inside an HTML element using the element's innerHTML property. However, before writing the output, we first need to select the element using a method such as getElementById(), as shown 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'll explore HTML element manipulation extensively in the chapter dedicated to JavaScript DOM manipulation.