Photograph of an audio plug board in front of a screen

When it fails, JavaScript most often dies with barely a whimper. While this is generally a good thing – a failed script won’t usually blow up your page – it can also make finding JavaScript errors a frustrating and time-consuming exercise.

In the early days of web development, bug tracking was often accomplished by inserting variable values in alert() windows, which would act as primitive indicators of script behaviour. Today, with many more scripts on web pages, we need much more powerful ways to write and test JavaScript. console, originally developed as part of the Firebug browser extension, now has its own API, and is invaluable for web developers at every skill level.

Bringing Up The console

While every vendor supports it, the console looks slightly different from one browser to the next, and is reached in a slightly different way in each:

  • In Chrome: ⌘-Option-J
  • In Firefox: ⌘-Shift-J
  • In Safari: Ensure that the Developer Menu option is on in Advanced Preferences; use ⌘-Option-C to bring up the console.

Part Scratchpad, Part Report Card

The console fulfills many tasks. It is, among other things:

  • An area for JavaScript to report errors
  • A “scratchpad” area to test code before implementation
  • A place for page scripts to output status and tracking information

I’ll discuss many more possible uses for console in future articles; for now, let’s take a quick look at the simplest of these features.

Start up a console, load a basic valid HTML page, and type the following into the console window:

document.body

Note that the console returns to you the body element, including all of its markup and text. An empty document would return:

<body></body>

Now let’s take it a little further:

document.body.style.backgroundColor = "red";

Note that this immediately changes the background of the page: you’re using JavaScript to directly write CSS in real time. Neat, huh?

Screenshot of the Chrome console window

Used in this way, the console becomes an excellent tool for playing with and learning JavaScript. Of course, all of this code, and any effect associated with it, disappears as soon as you refresh the page. We’ll look at using the console for working with real scripts on pages next.

Error Catching

Used as a catchment for errors, the console becomes even more useful. For example, write a script directly on a web page:

artists = ["Daft Punk","DJ Shadow","Amon Tobin"];
artists.push("Front Line Assembly");
console.log("The artists array contains " + artists.length + " elements");

Load the page, and switch to the console window. With console.log() you can “echo out” any variable, or the result of any action.

You can use the console for a lot more than these simple tasks, but I hope this will provide a good start for beginners.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.