Debug Your JavaScript Code in Real-Time

How a single line of code saved JavaScript

Jordan Scales
friendship .js
Published in
3 min readMar 19, 2014

--

You write a block of JavaScript, but when you run it, it doesn’t work. You poke and poke for hours on end, but just can’t vertically center that pesky div. Is it even possible? Some say it isn’t. Eventually you give up and delete your entire codebase — start all over.

We’ve all been there. Facebook did it, Google did it, Yahoo’s doing it. It’s a part of life, but when you think about it, there must be a better way.

This guide will show you how to find those pesky bugs in your JavaScript so you don’t have to delete your codebase.

Tools of the Trade

Integrated Development Environments — or IDEs — like Microsoft’s Visual Studio offer a suite of tools to developers such as syntax highlighting, code completion, and the ability to develop a profound amount of patience. Some of the most useful features, however, are the debugging tools.

A screenshot from Visual Studio 2014

Many IDEs support breakpoints, which allow us to pause the execution of our program and view the values of all of our variables, in real time.

Now JavaScript, due to a core philosophy of bare-metal development and togetherness, does not have IEDs and their fancy breakpoint utilities, but it does support the ability to copy features.

Give me a break, what’s the point?

First off, let’s talk about how clever that title is. What makes breakpoints so valuable? Well, have you ever looked a code segment like this:

And thought, “If only there was a way where I could see what value x held at a given time.” Well, there is a way, and it’s called an alert.

The alert command enables our application to produce real-time status updates — like Twitter for JavaScript! Here’s an example from my bank’s website:

Using this, we can record the values of our variables and see if they match the expected behavior. No more guesswork, the truth is laid out right before our eyes.

So how can we incorporate alert into our workflow? I’ve provided a template below which I use to start every piece of code I write.

To use this template, simply save it as template.js and open it in your favorite text editor. If you’re using vim, type:

And if you’re using emacs, enter the following:

Then just place your code between the various alert statements and run it to see the result of x after each line.

At this point you’ll have a responsive codebase that will alert you of the changes in x after every line — it will never leave your sight.

So say goodbye to bugs once and for all, and say hello to a new era of debugging in the world of JavaScript.

--

--

Jordan Scales
friendship .js

JavaScript clickbait enthusiast. Giving you superpowers.