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 a HTML file to run JavaScript Commands
Explanations of Commands
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 an example of a HTML file with the html, head, and body tags defines. 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. Below is a HTML file that is structured to use the "document.write()" command:
<!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: