When you're developing in JavaScript, it can be helpful to debug your code
at various points to see what's happening. Let's look at some ways you can examine the state of
your JavaScript code. One of the main differences between debugging PHP and JavaScript is that PHP
is a server-side language, so you can log messages to a file on the server. JavaScript, on the other
hand, is a client-side language, so you can't easily log messages to a file in the same way.
Fortunately, there are ways to examine the state of your JavaScript code using the browser's
developer tools, specifically the Console tab. Most modern browsers come with built-in developer
tools that allow you to inspect and debug the elements of a web page. Depending on the browser
you're using and the operating system you're on, you can usually open the developer tools by
pressing specific keys like F12, Ctrl+Shift+I, or Command+Option+I. If you're not sure how to
open the developer tools in your browser, you can find handy instructions on the MDN WebDoc site
under Guides, Common Questions, Tools and Setup, What are browser developer tools?
Once you have developer tools open, switch to the Console tab, which is where any errors on the page
are logged. It is also where you can log messages from your JavaScript code to help you debug it.
A Console object is what allows you to log messages to the browser's console.
It has several methods you can use to log different types of messages. Here are a few of
the most commonly used methods. The Console log method is the most popular, as it can be used to
log pretty much anything to the console. You can pass all sorts of data types to it, such as strings,
numbers, arrays, or even objects. Here is an example of logging a simple string variable to the console.
If you open developer tools and select the Console tab, the contents of the variable will be logged
to the console. The Console output also includes a link to the location of the code in the source
file, which can be helpful for tracking down where the message was logged from. You can also log more
complex data types, such as arrays or objects. When viewing this in the Console, you'll see an array
and object logged as expected. You're also able to expand the array or object and see its properties,
as well as any JavaScript methods that are available on that data type.
There are a number of other methods that you can use to log messages to the console,
such as ConsoleError, ConsoleWorn, and ConsoleInfo. One of the most underused methods is ConsoleTable,
which logs an array or object as a table, making it easier to read. This is especially useful when
you have an array of objects, and you want to see the data in a more readable format.
To read more about the browser's console object and its methods, make sure to visit the MDN Web Docs
page. It contains a full list of all the console methods, as well as useful examples.