Using the browser console
You may have seen this already, or not, but web browsers have a built-in option to see the code that makes the web page you are on possible. If you hit F12 on a Windows computer while you are in the web browser, or you right-click and select Inspect on macOS systems, you will see a screen appear, similar to the one in the following screenshot.
It might work slightly differently on your browser on your machine, but right-clicking and selecting Inspect generally does the trick:
Figure 1.1: Browser console on the Packt website
This screenshot contains multiple tabs at the top. We are now looking at the element tabs, which contain all the HTML and CSS (remember those?). If you click on the console tab, you will find at the bottom of the panel a place where you can insert some code directly. You may see some warnings or error messages in this tab. This is not uncommon, and don't worry about it if the page is working.
The console is used by developers to log what is going on and do any debugging. Debugging is finding the problem when an application is not displaying the desired behavior. The console gives some insights as to what is happening if you log sensible messages. This is actually the first command we are going to learn:
console.log("Hello world!");
If you click on this console tab, enter the first JavaScript code above, and then hit Enter, this will show you the output of your code therein. It will look like the following screenshot:
Figure 1.2: JavaScript in the browser console
You will be working with the console.log()
statement a lot throughout the book in your code to test your code snippets and see the results. There are also other console methods, such as console.table()
, that create a table when the inputted data can be presented as a table. Another console method is console.error()
, which will log the inputted data, but with a styling that draws attention to the fact that it's an error.
Practice exercise 1.1
Working with the console:
- Open the browser console, type
4 + 10
, and press Enter. What do you see as the response? - Use the
console.log()
syntax, placing a value within the rounded brackets. Try entering your name with quotes around it (this is to indicate the fact that it's a text string—we'll get to this in the next chapter).