The console object is the recommended way to log errors, messages, and information about what’s going on. All browsers have consoles and are accessible via the console object.
Clear your script and add this bit of code.
console.error( 'This is an error message.' );
console.info( 'This is an info message.' );
console.log( 'This is a log message.' );
console.warn( 'This is a warning message.' );
In our example, we use 4 methods which are available in the console object. They all basically output a message into the console, but they all have different meanings in each browser. Error message are usually displayed in red text or have an icon next to it display it’s significance.
Logging messages are a great way to debug code. Let’s take a look at this example.
console.log( 'Script started' );
var num = 10;
console.log( 'Variable num created with the value ' + num );
if( num == 9 )
document.write( num );
console.log( 'Message outputted' );
console.log( 'Script finished executing' );
In this example, we just log at what stage our code is executing. By doing this, we can make sure to check if certain parts of code is running the way we want them to. This is a much better alternative than alerting a message or outputting a message into the document directly.
Logging messages into the console does not affect the website in anyway. It’s also recommended you only log messages during the development process of your website. It serves little to no purpose in live production code.
You’ll be using the console object often during development phases. For more information on the console object and debugging in general, then go here.