Debugging JavaScript

Debugging is the worst part of JavaScript for some, and the best part for others. One thing is sure though, it is an inevitable challenge for contenders in both groups.

You are here because you want to learn more about debugging JavaScript.

In this post, I will show you common bugs that can occur with JavaScript (JS) and ways to solve these challenges using Google Chrome Devtools.


Subscribe to my Newsletter


First, watch this great video by Google to introduce you to debugging.

Opening the JavaScript Console

To open the JavaScript console, just press CTRL + Shift+ J on Windows, or Command + Option + J on Mac.

JavaScript Methods

You can interact with objects in the console using console.log() and console.clear(). The console.log() method prints what is is passed as an argument between the parentheses. The console.clear() method will clear the browser console.

var myVar = "Hello World!";
console.log(myVar);
//Hello World

console.clear();
//Console was cleared

These are super useful debugging tools that you can input at strategic points in your code to preview the values of variables.

Common JavaScript Bugs

Here, I will show you some of the most common JavaScript bugs that you can find within your code.

1. Working With The Wrong Data Types

A lot of bugs in code are caused because of the interaction between variables of different types (like a string with an number). To print the type of a variable, use typeof.

JavaScript recognizes seven data types: Null, Undefined, Boolean, Number, String, Symbol and Object

var myStr="Hello World!"
console.log(typeof myStr); //String
console.log(typeof []); // Object
console.log(typeof 0); // Number

2. Misspellings of Variables and Function Names

Missplelling is so common (see what I just did ?) that it needs its own section in this guide. Wrong capitalization and missing letters are the enemies of JS.

var myVar = "Camel Case"
console.log(MYVAR); //Wrong Capitalization
/*VM171:2 Uncaught ReferenceError: MYVAR is not defined
    at <anonymous>:2:13*/

Make sure that you use a code editor that handles autocomplete.

Code editiors help coders reduce misspelled variable and function names using autocomplete, like in this example from VisualStudio’s Intellisense functionality.

IntelliSense demo
Source: VisualStudio

3. Opening and Closing Brackets

Brackets [], () and {} must come in pairs with an opening bracket and a closing bracket.

This is another error that we see quite often.

var myArray=[1,2,3;
//Uncaught SyntaxError: Unexpected token ';'

This error is cause because we have forgot the closing bracket.

We can also have a problem if we forget to add the parentheses after a function call. 

function myFunction() {
print("Hello World");
}
var caseOne = myFunction; //Assigns the function to a variable
vare caseTwo = myFunction(); //Assigns the result of the function to a variable

4. Assignments Operators

In JavaScript, = is not the same as == or ===

The equal sign (=) is an assignment operator, which mean that you assign a value to a variable, while the double and the triple equal signs check for equality (values are equal) for the former and strict equality (value and type are equals) for the latter.

It is important to double check places where the equal sign is used in place of an equality operator.

5. Wrong Quotation Marks

Different quotation marks can be used in JavaScript to enclose quotation marks within other quotation marks.

For example, double-quotes “” can be enclose within single-quote ” that can be enclosed within backticks “. This solves the problem qhen you want to write quotes in a string.

var quote = `You wrote: ‘JFK have said “Ask not what your country can do for you”‘.`

If you would use only double quotes, you would end up with a real problem.

var quote = "You wrote: "JFK have said "Ask not what your country can do for you""."

6. Indexing Errors

JavaScript uses indexing on base zero (0). This means that if you want to get the first value of an array, you should use the index #0.

Example.

myArray[0] equals the position 1 of the array myArray, myArray[1] equals the position 2 up to myArray[-1] that equals the last value of the array.

This often causes an “index out of range” reference error in JavaScript because of a result that is off by one.

//Source: freeCodeCamp
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let len = alphabet.length;
for (let i = 0; i <= len; i++) {
// loops one too many times at the end
console.log(alphabet[i]);
}
for (let j = 1; j < len; j++) {
// loops one too few times and misses the first character at index 0
console.log(alphabet[j]);
}
for (let k = 0; k < len; k++) {
// This is the right way to do it
console.log(alphabet[k]);
}

This error is often caused by for loops. You can work around this error using the map() and the spread ... functions that will iterate over each value of an array instead of using the for loop.

7. Global VS Local Variable Assignment

Global variables are created outside of a function to be used anywhere outside the function, and local variable are created inside a function to be used by the function.

//Global
var myGlobalVar = "This is a global variable";
//Code here can use myGlobalVar
function myFunction(){
//Code here can also use myGlobalVar
}
//Local
//Code here CAN'T use myLocalVar
function myFunction(){
var myLocalVar= "This is a local variable";
//Code here CAN use myLocalVar
}

8. Infinite Loops

An infinite loop is a loop that will keep running forever  until it crashed your browser or computer, like the one below. 

// for (var i = 0; i < 10; ) {}

Whenever you run through an infinite loop in JavaScript, you can kill it by closing the browser tab,  by killing the task using Chrome Task Manager (Shift+Esc), or by clicking pause in the source panel like shown in the video at the beginning of this post.

There are multiple ways to detect infinite loops. 

One of those ways is to keep a check on the time spent inside a loop.

var startTime = Date.now();
for (var i = 0; i < 10; ) {
 if (Date.now() - startTime > 1000) {
   break;
 }
}

9. Handle JavaScript Errors with Try and Catch

As we have seen, there are many ways to produce errors in your code. 

One google way to catch those errors is to use the try and catch syntax.

try {
alerting("It is a lovely day");
}
catch(error) {
console.log(error);
}

To learn more about the try and catch syntax, just look at this great post by codeburst.

Conclusion

If you are looking at debugging SEO, make sure that you watch Martin Splitt’s live debugging session.

We have seen the most common bugs that we can encounter in a JavaScript program.

It is now up to you to make sure that you can debug your own code as you go.

If you are interested in programming for SEO, check out this complete Python SEO series, and the beginner guide to help you learn python.

4.5/5 - (2 votes)