How To Debug Javascript (A Very Simple Guide)

Welcome to a tutorial on how to debug Javascript. Oh no! An error occurred, what is to be done next? Sadly, the immediate reaction of some beginners is to go into denial – Debugging is difficult, I will just report “it doesn’t work” and things will be magically fixed. Well, no.

The most basic form of debugging Javascript is to:

  • Open the developer’s console (press F12 in most modern browsers).
  • Click on an element, submit a form, or refresh the page to replicate the error – See the error message that is being shown in the console.
  • Trace and fix the error.

That’s all, really. Believe it or not, just learning how to read an error message can solve a lot of silly mistakes. Sharing the error messages will also get you better answers than “no idea what went wrong”. If you are ready to learn more debugging powers – Read on!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/simple-javascript-debug/” title=”Very Simple Javascript Debugging” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

REALLY SIMPLE DEBUGGING

All right, let us now start with a really simple debugging process in this section.

 

STEP 1) OPEN THE DEVELOPER’S TOOLS

As in the introduction above, the first step is to open the developer’s tools. Most modern browsers should have this built-in and can be opened by pressing F12.

 

 

STEP 2) READ THE ERROR MESSAGE

<script>
function foo () { alert("bar!"); }
</script>

<!-- SHOULD BE FOO(), NOT FOOZ() --> 
<input type="button" value="test" onclick="fooz()">

The next step is to switch to the “console” tab and see the error message. For example, we have a silly typo mistake in the onclick here. When we click on the button, an error will be registered in the console.

Yep, it’s that simple – You now have an error message and eyes on what went wrong.

 

STEP 3) TRACE & FIX THE ERROR

Notice how the console gives you the exact file and line number test.html:18 of where the error occurred? fooz is not defined at HTMLInputElement.onclick may not be a “straightforward error message”, but just think a little bit – function fooz() is not defined. The mistake should be clear as day now.

 

 

COMMON ERRORS

The error messages may not be straightforward, so here are a few of the common errors, and what they mean.

 

SYNTAX ERROR

var arr = ["Foo", "Bar"};
var txt = "Hello';
Uncaught SyntaxError: Unexpected token ‘}’

One of the most common beginner mistakes – Missing and wrong brackets, commas, sometimes even using the wrong operators.

 

TYPE ERROR

var num = 999;
num.toLowerCase();
Uncaught TypeError: num.toLowerCase is not a function

Another common newbie mistake – Using functions and statements that are meant for the wrong data type. E.g. toLowerCase() only works on strings, not numbers.

 

REFERENCE ERROR

var numA = 999;
var numB = 888;
var numC = numa + numB;
Uncaught ReferenceError: numa is not defined

Yet another common mistake – Referring to functions and variables that are not defined. Yes, take note that variable names in Javascript are case-sensitive.

 

 

RANGE ERROR

var arr = ["Foo"];
arr.length = 99999999999999999999999999999999999;
Uncaught RangeError: Invalid array length

A not-so-common error, when we try to set a length or range that is bigger than the allowed limits.

 

URI ERROR

var url = "http://site.com?foo=\uD800";
url = encodeURI(url);
Uncaught URIError: URI malformed

When we try to encode a funky URI.

 

INTERNAL ERROR

Ok, this one is hard to replicate. This happens when we push Javascript beyond the limits. For example, a string so long that it went out-of-memory.

 

 

ERROR TRACING & TIPS

Some errors are easy, just go to the script and eyeball a few lines of code. But how do we deal with the complicated ones? Here are a few more tricks.

 

CONSOLE LOG & ERROR

var arr = ["Foo", "Bar"]; 
console.log(arr); 
console.log("This is a message");
console.error("Error message");
  • console.log() can be used to output any message or variable in the developer’s console.
  • The cousin console.error() will also output a message in the developer’s console, but in big red bold.

 

CONSOLE TABLE

var data = {
  foo : "Bar",
  hello : "World",
  doge : "Good Boy",
  cate : "Evil",
  numbers : [1, 2, 3, 4]
};
 
console.log(data);
console.table(data);

console.log() is cool, but it can sometimes be difficult to read for arrays and objects. So in this case, we use console.table() instead.

 

TYPE OF

var arr = ["Foo", "Bar"]; 
var numA = 123;
var numB = "456";
var fn = function () {};
console.log(typeof(arr));
console.log(typeof(numA));
console.log(typeof(numB));
console.log(typeof(fn));

Javascript is a loosely-typed language, but that does not mean data types do not exist. What is the data type of a variable? Use typeof() to find out.

 

 

DEBUGGER

var first = "Hello World";
debugger;
 
var second = "Foo Bar";
debugger;
 
var third = "Doge Moon";

What is happening in the script at a certain point?

  • Use debugger to pause the script at that specified line.
  • Then use the developer tools to give you a breakdown of what is happening at that point.
  • Hit on the “resume” button to continue running the script.

 

STACK TRACE

function first () { 
  alert(1 + second());
}
function second () {
  console.trace();
  return 2;
}
first();

In a big project, it is common for functions to call functions. So which other functions are being called? Use console.trace() to find out.

 

PERFORMANCE

console.time("Demo");
var test = 1;
for (let i=0; i<9999999; i++) { test++; }
console.timeEnd("Demo");

A segment of the script is performing poorly? Use console.time() and console.timeEnd() to find out.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY

Function Description
console.log() Output a message and/or variable to the developer’s console.
console.table() Output an array or object in (human-friendly) table form.
console.trace() Do a stack trace, what called this function?
typeof() Gives you the data type of a variable.
debugger() Pauses the script at this point, gives an overview of the status.
console.time(NAME) and console.timeEnd(NAME) Starts timing the script.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to smash some nasty bugs, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *