Oops, I did it again: debugging common JavaScript errors

Original author: Ali Spittel
  • Transfer


Sometimes writing JavaScript code is difficult, and sometimes it’s just scary, which is familiar to many developers. In the process, errors inevitably arise, and some of them are often repeated. The article, designed for novice developers, talks about these errors and how to solve them. For clarity, the names of functions, properties and objects are taken from a popular song . All this helps to quickly remember how to fix common errors.

We remind you: for all readers of “Habr” - a discount of 10,000 rubles when registering for any Skillbox course using the “Habr” promo code.

Skillbox recommends: Practical course "Mobile Developer PRO" .

TypeError: property not defined


let girl = {
    name: "Lucky",
    location: "Hollywood",
    profession: "star",
    thingsMissingInHerLife: true,
    lovely: true,
    cry: function() {
        return "cry, cry, cries in her lonely heart"
    }
}
console.log(girl.named.lucky)

The sample code above throws an Uncaught TypeError: Cannot read property 'lucky' of undefined error. The problem is that the girl object does not have a named property, although there is a name property. And since the property girl.named is not defined, it is impossible to access it, because formally it does not exist. But if you replace girl.named.lucky with girl.name, then everything will work and the program will return Lucky.

Read more about the properties here .

Methods to Fix TypeError Errors


TypeError errors occur when a programmer tries to perform actions on data that does not match a particular type. As an example, use .bold (), request an undefined property, or call a function that is not really a function.

So, if you try to call girl (), then an Uncaught TypeError error will appear: yourVariable.bold is not a function and girl is not a function, because in fact the object is called, not the function.

In order to eliminate errors, you need to study the variables. So what is girl? And what is girl.named? You can find out if you analyze the code, display the variables using console.log with, the debugger command, or by calling the variable name in the console. You need to make sure that it is possible to operate with the data type that is contained in the variable. If it does not fit, change it, for example, add a condition or try..catch block and get control over the operation.

Stack overflow


If you believe the authors of the words of the song Baby One More Time (this is Britney Spears, huh), then the word hit in this context means the desire of the singer to be called again (here is an explanation of the context of the song, approx. Translator). It may well be that this desire will lead to an increase in the number of calls in real life. But in programming, this is a recursion that can cause an error if the call stack overflows.

The errors are as follows:

Error: Out of stack space (Edge)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded (Chrome)

Stack overflow occurs if the developer did not take into account the base case in recursion or if the code does not access to the intended case.

function oneMoreTime(stillBelieve=true, loneliness=0) {
    if (!stillBelieve && loneliness < 0) return
    loneliness++
    return oneMoreTime(stillBelieve, loneliness)
}

In this case, stillBelieve can never set to false, so oneMoreTime will be called every time, but the function will never end.

If you start to hope for two friends, this will reduce loneliness (loneliness), and you can not wait for the call.

function oneMoreTime(stillBelieve=true, loneliness=0) {
    if (!stillBelieve && loneliness < 0) return
    loneliness--
    stillBelieve = false
    return oneMoreTime(stillBelieve, loneliness)
}

As an example, there are cases with infinite loops, when the system does not give an error message, and the page on which the JavaScript code is executed simply freezes. This happens if the while loop does not have a termination condition.

let worldEnded = false
while (worldEnded !== true) {
  console.log("Keep on dancin' till the world ends")
}

You can solve the problem as follows:

let worldEnded = false
while (worldEnded !== true) {
  console.log("Keep on dancin' till the world ends")
  worldEnded = true
}

Debug endless loops and recursions


If you have a problem with an infinite loop, in Chrome or Edge you need to close the tab, and in Firefox, close the browser window. After that, you need to carefully analyze the code. If you cannot find the problem, you should add the debugger command to the loop or function and check the value of the variables. If the result is not as expected, then replace, it can be done easily.

In the example above, debugger should be added as the first line of a function or loop. Then you need to open the debug tab in Chrome by analyzing the variables in scope. Using the next button, you can track their change at each iteration. Doing all this is simple, and in most cases the problem is.

You can read more about all this here ( for Chrome ) and here ( for Firefox ).

Syntax error


One of the most common JavaScript errors is SyntaxError. Avoid them help extension text editor. So, Bracket Pair Colorizer marks the brackets in the code in different colors, and Prettier or a similar analysis tool makes it possible to quickly find errors. The best option to reduce the likelihood of SyntaxError is minimal nesting.

Share in the comments: what do you do in order to avoid mistakes or quickly detect and eliminate them?

Skillbox recommends:


Also popular now: