11. Console Logging Basics

In This Chapter

  • Learn how to go beyond alerts for displaying results

  • Understand how the console works

  • Learn the variety of logging solutions you have at your fingertips

When you are writing code, you will often find yourself in one of two situations. One situation is where you wonder if the code you just wrote is going to run at all. In the other situation, you know your code runs, but it isn’t running correctly. There is something wrong...somewhere.

Image

In both of these situations, what you need is some extra visibility into what your code is doing. A timeless approach for bringing this visibility involves the alert method:

let myButton = document.querySelector("#myButton");
myButton.addEventListener("click", doSomething, false);

function doSomething(e) {
  alert("Is this working?");
}

Using the alert method isn’t bad. It works fine for simple situations, but as your code starts to do more, relying on them doesn’t work as well. For starters, you’ll probably go insane from dismissing the large number of dialogs that keep popping up while your code is running! You’ll also want an easy way to persist the messages you are seeing. The fleeting nature of our alert dialogs makes any sort of long-term logging like that difficult.

In this tutorial, we’re going to look at one of the greatest inventions of all time that makes it easy to help us figure out what our code is doing. We are going to be learning about something known as the console.

Onward!

Meet the Console

Even if you think you write the most perfect JavaScript, you’ll be spending a fair amount of time in what is known as the console. If you’ve never used the console before, it is part of your browser’s developer tools where all sorts of text and stuff gets printed for you to see and (occasionally) interact with.

It will look a little bit like what is shown in Figure 11.1

Image

FIGURE 11.1

Meet the console.

At a very high level, your console helps with a bunch of things:

  • You can read messages you have told your code to log and display

  • You can modify your application state by setting (or overwriting) variables and values

  • You can inspect the value of any DOM element, applied style, or code that is accessible and in scope

  • You can use it as a virtual code editor and write/execute some code just for kicks

In this article, we won’t focus on all the things your console is capable of doing. Instead, we’re just going to take it easy and gradually get you comfortable with using the console to just display messages. We will cover all of the crazy console-related things eventually, so don’t worry.

Displaying the Console

The first thing we are going to do is get your console up. The console is a part of your browser’s developer tools. The way you bring up your browser developer tools is by fiddling with your browser’s menus or by using the handy keyboard shortcuts. From inside your browser, press Ctrl + Shift + I on Windows or Cmd + Alt + I on Mac to bring up the developer tools.

Depending on your browser and platform, each of your developer tools will look a little different. The important thing is to find the Console tab and make sure the console gets displayed.

When you bring up the console in Chrome, you’ll see something like what you see in Figure 11.2.

Image

FIGURE 11.2

The Chrome console.

On Safari, the console will look a bit like Figure 11.3.

Image

FIGURE 11.3

The Safari console.

Firefox’s console looks like what is shown in Figure 11.4.

Image

FIGURE 11.4

The Firefox console.

Bringing up the console in Microsoft Edge will look like Figure 11.5.

Image

FIGURE 11.5

The Edge console.

The thing I want to highlight is that it doesn’t matter which browser you use. The console looks and functions pretty much the same on all browsers. Just bring up the console in your favorite browser and get ready to start actually using the console in the following sections.

If You Want to Follow Along

Now, you can just read the following sections and learn a whole bunch of console-related things without lifting a finger. If that is what you would like to do, then skip all of this and jump to the next section.

On the other hand, if you want to get your hands a bit dirty and see some of the console shenanigans for yourself on your screen, create a new HTML document and add the following HTML, CSS, and JavaScript into it:

<!DOCTYPE html>
<html>

<head>
  <title>Console Stuff</title>

  <style>
    #container {
      padding: 50px;
    }

    #myButton {
      font-family: sans-serif;
      font-size: 24px;
      font-weight: lighter;
      background-color: #FFF;
      border: 3px #333 solid;
      padding: 15px;
    }

    #myButton:hover {
      background-color: aliceblue;
    }

  </style>
</head>

<body>
  <div id="container">
    <button id="myButton">click me</button>
  </div>
  <script>

    let myButton = document.querySelector("#myButton");
    myButton.addEventListener("click", doSomething, false);

    function doSomething(e) {
      alert("Is this working?");
    }
  </script>
</body>

</html>

What we have here is a really simple HTML page with a button that you can click. When you click on the button, an alert dialog (the same one we described earlier) will appear. In the following sections, we’ll modify this example to help bring some of the console-related things to life!

Console Logging 101

The first thing we are going to do is tell our console to display things on screen. This is no different than what we did with the alert statement earlier, and it is almost just as easy. The key to all of this is the Console API. This API contains a bunch of properties and methods that allow you to display things to your console in a variety of ways. The first and probably most popular of these properties and methods is the log method.

Meet the Log Method

At its most basic level, the way you use the log method is as follows:

console.log("Look, ma! I'm logging stuff.")

You call it via the console object and pass in the text that you want to display. To see this in action, we can replace the alert from our example with the following:

function doSomething(e) {
  console.log("Is this working?");
}

When you run this code, take a look at your console after clicking on the click me button. If everything worked out properly, you will see the “Is this working?” text displayed inside it as shown in Figure 11.6.

Image

FIGURE 11.6

The click me button displayed!

If you keep clicking on the button, you’ll see more instances of “Is this working?” getting logged as shown in Figure 11.7.

Image

FIGURE 11.7

Each button click will end up getting represented in our Console.

How that looks will depend on the developer tools you are using. You will probably just see a counter to the left of your initial message getting incremented as shown in the screenshot. You may see the text “Is this working?” getting duplicated in each line as well. Don’t be alarmed if what you see doesn’t exactly match what you see in my screenshots. The important detail is that your call to console.log works and is logging messages for you to see in the console. Also, these messages aren’t read only. You can select them. You can copy them. You can even print them and frame them on the wall behind you.

Going Beyond Predefined Text

Now that you’ve just seen the basics, let’s go a bit deeper. When using the console, you aren’t limited to only printing some predefined text. For example, a common thing you might do is print the value of something that exists only by evaluating an expression or accessing a value. To see what we mean by this, make the following change to your doSomething function:

function doSomething(e) {
  console.log("We clicked on: " + e.target.id);
}

What we are doing here is telling our console to display the text “We clicked on” in addition to the id value of the element we clicked on. If you preview these changes in your browser, click on the click me button again, and check out what is shown in the console, as in Figure 11.8.

Image

FIGURE 11.8

The id of the button we clicked on is displayed!

The id value of the button you clicked on is displayed in addition to our predefined text. Now, getting the id value of an element is probably not the most exciting thing you might want to print, but you can print pretty much anything that would look good when represented as text. That’s powerful!

Displaying Warnings and Errors

It is time to look beyond the log method! Our console object provides us with the warn and error methods that allow us to display messages formatted as warnings and errors, respectively, as shown in Figure 11.9.

Image

FIGURE 11.9

We can show errors and warnings...like a boss!

The way you use these two methods is no different from how you used the log method. Just pass in whatever you want to display. You can see an example of how to use these methods in the following snippet:

let counter = 0;

function doSomething(e) {
  counter++;

  console.log("Button clicked " + counter + " times!");

  if (counter == 3) {
    showMore();
  }
}

function showMore() {
  console.warn("This is a warning!");
  console.error("This is an error!");
}

When this code runs and our button is clicked three times, the showMore function gets called. Inside that function, all we have is our console warning and error:

function showMore() {
  console.warn("This is a warning!");
  console.error("This is an error!");
}

Now, there is something cool about warnings and errors that goes beyond just their appearance compared to their more boring log counterparts. You can expand them in the console and see the full stack trace of all the functions your code took before hitting them as shown in Figure 11.10.

Image

FIGURE 11.10

Seeing more details for our errors!

For large pieces of code with a lot of branching, this is really useful. The warn and error methods provide an excellent way for us to better understand the twisted paths our code took into getting into whatever state it ended up in!

The Absolute Minimum

The console provides you with one of the best tools you have for understanding what your code is doing. Displaying messages is only one part of what the console allows you to do. Within our narrow focus on just displaying messages, there is a whole lot more that we can cover than what we’ve seen so far. We’ll cover more things the console does later, but the few console techniques you’ve seen here will take you far in helping you find and squash bugs in your code.

If you have any questions, feel free to post them on the forums at https://forum.kirupa.com. I and others will be extremely totally happy to help you out!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.149.168