Anyone learning programming eventually finds it necessary to check the correctness of code. The typical task of most scripts is to retrieve data when all code blocks are executed. Especially in regards to "Learn-how" scripts, since at the initial stages of learning JS this is the easiest way of supervision.

JavaScript doesn't have a unified format for data output. There are different options depending on the tasks at hand. In this tutorial, we look at the syntax and their characteristics with the aim of learning how to select the appropriate JavaScript Output method.

Method 1. Console.log()

Almost all modern web browsers have a Console. As a rule, it is a part of developer and debugging tools for web pages. It is used to display technical information about a page, in particular, error messages in code execution.

But Console can also be used to enter JS code and get the results of its execution if you refer to certain parts of the page. Therefore, the functionality of the browser console is an integral part of any environment for JavaScript code execution. It makes this method the most popular one for "outputting" in JavaScript.

Syntax

console.log();

Example

This method has a simple syntax. There we must put a variable in parentheses, i.e. the text to display.

let text = 'Console test';
console.log(text);

It is also possible to set its content manually, following the rules for different data types.

let text = 'Console test';
console.log(12345);

Method 2. GetElementById()

This method can be used only if you want to output data into the target part of the HTML page. HTML is a special language used to determine the position and execution order of web page content, including JavaScript code. 

Therefore, JavaScript has a method that allows you to read from HTML elements as well as write it. Therefore, to work with this method you need to know the identifier of the content element you aim to modify.

Syntax

document.getElementById("elementID").innerHTML = 'Some output';

Example

You need to wrap the id element in parentheses, and enter data to be displayed after =. In our case this is a string "Some text" which will be printed into the <p> tag. 

Please note that if the element already contains data, it will be replaced with the new incoming one. 

<!DOCTYPE html>
<html>
 <body>
   <p id="ID1"></p>
   <script>
     document.getElementById("ID1").innerHTML = "Some output";
   </script>
 </body>
</html>

Method 3. Document.write()

This method implies adding a string of text to the document stream. It is recommended to use it only in simple scripts and algorithms, when you only start to learn JavaScript and have to quickly check the output. 

Syntax

document.write();

Modifying a document that has already been loaded without calling document.open() will automatically call document.open()

The document.open() method opens a document for writing. Please note the following when you call up the document.open() method:

  • All event listeners currently registered on the document, nodes inside the document, or the document window are removed.

  • All existing nodes are removed from the document.

After writing, you need to call document.close() method to finish the page loading. Here is the chain of methods to call for executing the document.write() method.

document.open();
document.write();
document.close();

Example

<html>
 <head>
   <title>My example</title>
   <script>
     function exmplContent() {
       document.open();
       document.write("<h1>my document.write() example</h1>");
       document.close();
     }
   </script>
 </head>
 
 <body onload="exmplContent();"></body>
</html>

Method 4. Alert()

This method is based on using the built-in browsers functionality, in this case - Alert boxes. It is part of Popup Boxes - a special kind of pop-up window that blocks interaction with a web page until the user takes a specific action. Alert Box allows you to display the specified text under which there will be the OK button. 

Only clicking this button will hide the pop-up window and restore the ability to interact with the webpage. This pop-up does not depend on the semantic content of the page, but the command to initialize it must be placed in the page script structure before starting its execution.

It is also worth mentioning that this method is used primarily to display messages that are important to the user. Therefore, it is not recommended applying this method to output information, e.g. greetings or results of command execution.

Syntax

This command accepts data just like the others - in parentheses and proper  formatting.

window.alert("This text will be displayed to the user");

Example

window.alert("Hello, me dear User!");
alert("Hello, me dear User!");

Practical examples

  • Example 1. Output any text to the console.

Solution 1

First, let's create a variable called message. Then we will set a text value to it and enter the text required for output in quotation marks. The final step is to write the console.log() method and put the variable we created in parentheses.

let consolMessage = 'Console output';
console.log(consolMessage);

Solution 2

You can also solve this by specifying the text required for output directly in the console.log() method parentheses.

console.log('Console output');
  • Example 2. innerHTML.

Change the value of the HTML page element and output it.

Solution

To make it easier to understand, let's go step by step.

Step 1. Make the boilerplate for the HTML document. All further content on the page should be placed between the <body> tags.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
 </body>
</html>

Step 2. In the first line we create a <p> element we will refer to. After <p> element create a button, which will be changing the initial text of the <p> element by clicking on it. Write this code between the <body></body> tags.

<p id="myElementID">Output text</p>
<button onclick="solution()">Click to change text above</button>

Step 3. Create a solution() function to replace the initial content of the <p> element with "Here's the new output". Place your function into the <script></script> tags. 

<script>
   function solution() {
     document.getElementById("myElementID").innerHTML =
       "Here's the new output";
   }
</script>

And this is how will look all code blocks together:

<!DOCTYPE html>
<html lang="en">
 <head>
     <title>Document</title>
 </head>
 <body>
   <p id="myElementID">Output text</p>
   <button onclick="solution()">Click to change text above</button>
 </body>
 <script>
   function solution() {
     document.getElementById("myElementID").innerHTML =
       "Here's the new output";
   }
 </script>
</html>

After executing this code, a line with text and button will appear on the page. When you click on the button, the text of the top line will be changed to a new one.

  • Example 3. document.write().

Output your name.

 Solution

As in the previous exercise, create the boilerplate of the HTML page. Then place the document.write() method between the <script></script> tags. Don't forget to use document.open() and document.close() methods together with document.write()

However, if you don't write document.open() in your code, it will automatically be called. After writing, the document.close() will be called for telling the browser to finish page loading.

If you put your document.write() call within an inline HTML <script></script> tag, it will not call document.open(). But in our example we'll write document.open(), document.write(), and document.close().

<!DOCTYPE html>
<html lang="en">
 <head>
     <title>Document</title>
 </head>
 <body></body>
 <script>
   document.open();
   document.write("Here is my output with using document.write() method");
   document.close();
 </script>
</html>

Result

The text "Here is my output using document.write() method" will be displayed on the screen.

  • Example 4. window.alert()

Show users a pop-up notification with a custom text.

Solution

Step 1. Create an HTML page boilerplate.

<!DOCTYPE html>
<html lang="en">
<head>
 <title>Document</title>
</head>
<body>
 </body>
</html>

Step 2. Create a button that will activate our pop-up call method. Note that the button should be placed between the <body></body> tags.

<button onclick="solution()">Show me Alert box</button>

Step 3. Create a function that will activate the Alert box on click and add it to the JavaScript code block. Put this function into the <script></script> tags.

<script>
   function solution() {
     alert("This is the alert box for my output.");
   }
 </script>

Step 4. Put all code fragments into a single script.

<!DOCTYPE html>
<html lang="en">
 <head>
     <title>Document</title>
 </head>
 <body>
   <button onclick="solution()">Show me the Alert box</button>
 </body>
 <script>
   function solution() {
     alert("This is the alert box for my output.");
   }
 </script>
</html>

Result

The page will show the button labelled "Show me the Alert box". When you click it, the alert box will be displayed with the following text: "This is the alert box for my output".

Test yourself

  • Task 1

Create an HTML page where Alert Box content will be changed via innerHTML after clicking on the button.

Solution

<!DOCTYPE html>
<html lang="en">
<head>
  <title>My Document</title>
</head>
<body>
 <body>
   <p id="myElId">You need to change me!</p>
   <button onclick=" showMeText()">Show Alert box</button>
   <button onclick=" changeText  ()">Change the text</button>
   <script>
     function showMeText() {
       window.alert(document.getElementById("myElId").innerHTML);
     }
     function changeText() {
       document.getElementById("myElId").innerHTML =
         "You successfully have changed the text";
     }
   </script>
</body>
</html>
  • Task 2

Calculate the sum of three arbitrary numbers and print its result to the console along with some text.

Solution

let a = 68;
let b = 34;
let c = 15;
let sum = a + b + c;
console.log(`Sum = ${sum}`);
  • Task 3

Output the text using different ways (except document.write), numbering each mention of it. Make these operations start by clicking the button. 

<!DOCTYPE html>
<html lang="en">
 <head>
     <title>Document</title>
 </head>
 <body>
   <p id="myElId">Sample text</p>
   <button onclick="show()">Show Alert box</button>
 </body>
 <script>
   function show() {
     console.log("My output 1");
     document.getElementById("myElId").innerHTML = "My output 2";
     window.alert("My output 3");
   }
 </script>
</html>