Sitemap

Debugging JavaScript, part 1.

3 min readFeb 29, 2020
Press enter or click to view image in full size
Photo by Krzysztof Niewolny on Unsplash

JavaScript is considered to be a loosely typed language, one where you don’t have to specify what type of information will be stored in a variable in advance.

Some languages require you to declare a variable’s type before even running a program. This will tell you right away when a type is used in an inconsistent way. JavaScript considers types only when actually running the program, and even there often tries to implicitly convert values to the type it expects.

Also, JavaScript’s concept of bindings and properties is vague enough that it will rarely catch typos.

Because of these reasons, it will allow for sometimes too many nonsensical code to run, making the language very prone to bugs and errors.

Strict Mode

JavaScript can be made a little stricter by enabling strict mode. This is done by putting the string “use strict” at the top of a file or a function body. Here’s an example:

Press enter or click to view image in full size

Normally, when you forget to declare a variable, JavaScript will quietly create a global binding and use that. In strict mode, an error is reported instead.

Debugging

Once we notice there is something wrong with our program because it misbehaves or produces errors, the next step is to figure out what the problem is.

Get Gia Edgington’s stories in your inbox

Join Medium for free to get updates from this writer.

Sometimes it is obvious. The error message will point at a specific line of the program, and if we look at the error description and that line of code, we can often see the problem.

But sometimes the line that triggered the problem is simply the first place where a flaky value produced elsewhere gets used in an invalid way.

All modern browsers have a built-in JavaScript debugger. With a debugger we can set breakpoints and examine variables while the code is executing.

The console.log() method

We can use console.log() to display JavaScript values in the debugging window:

Putting a few strategic console.log calls into the program is a good way to get additional information about what the program is doing.

Setting Breakpoints

Browser come with the ability to set a breakpoint on a specific line on your code. When the execution of the program reaches a line with a breakpoint, this one is paused, and we will be able to inspect JavaScript values.After examining values, we can resume the execution of code .

The debugger Keyword

Another way to set a breakpoint is to include the debugger keyword, which will also pause the execution of JavaScript, and calls (if available) the debugging function.

If no debugging is available, the debugger statement has no effect.

With the debugger turned on, this code will stop executing before it executes the third line.