JavaScript Console
What is the Console?
The console is basically a terminal for JavaScript in the web browser. We can also use the console as an interactive place to interact and experiment with JavaScript.
Opening the Console
It depends on the web browser. On Google Chrome, right click, select "Inspect Element" and switch to the "Console" tab. Then, you should see the console.
Printing to the Console
To print to the console, we use the console.log()
function. As an example, go to any web page and open the console. In your console, type console.log("Hello World!")
. You should something like the following (again, depends on web browser):
Of course, we can also use console.log()
in our JavaScript code files. As an example, type the following into your script.js
file:
console.log("Running console.log from script.js")
Now, if you go into the console, you should see something like this:
console.log()
is useful for testing purposes.
Making an Error in the Console
To make an error in the console, we use the console.error()
function. For example:
console.error("You did something wrong!")
Once you run it, you should see:
Making a Warning in the Console
To make a warning in the console, we use the console.warn()
function. For example:
console.warn("You probably shouldn't do that.")
Once you run it, you should see:
Making an Informational Console Message
In addition to errors and warnings, we can also make informational messages in the console using the console.info()
function. For example:
console.info("Your response was recorded.")
Once you run it, you should see:
Clearing the Console
When the console gets too full, we can use the console.clear()
function to clear the console.