JavaScript: When and Where to use the commands console.log("") and document.write("") to Print Statements

JavaScript: When and Where to use the commands console.log("") and document.write("") to Print Statements

Overview

This short article explains when and where to use the commands "console.log()" and "document.write()" when coding in JavaScript to print statements.

Materials

  • Internet Browser - Microsoft Edge was used in this demo

  • Notepad, Command Prompt, Terminal, or IDE - A program to make and edit HTML files to run JavaScript commands

When to use console.log() and document.write()

Both "console.log()" and "document.write()" are commands used to print statements in Javascript. "console.log()" should only be used when working with an Internet Browser console while "document.write()" should only be used when working with HTML files.

Using the console.log() Command

As stated, the "console.log()" command only works when using the console in an Internet Browser. To find the console, open up an Internet Browser. On any tab, right-click and select "Inspect".

After clicking "Inspect", there are many options to choose from, including a "Console" option. By clicking the "Console" option, a shell appears that the user can interact with. Since this console shell is configured for the internet browser, running any commands will affect the browser directly or the web pages that it displays. Below is a full view of the "Console" in Microsoft Edge:

Here is where JavaScript commands can be entered. In the Console, type "console.log("Hello")" and press enter.

As shown it returns, "Hello".

Using the document.write() Command

Below is a HTML file with the html, head, and body tags. Within the body tag, script tags are defined since within script tags, JavaScript code can be written there. To output text on a HTML page by using JavaScript, the command "document.write()" can be used.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>

    <body>
        <script>document.write("Hello")</script>
    </body>
</html>

After configuring and saving the HTML file, open the file. If successful, a blank page with the word "Hello" should appear: