Oops, I did it again: Debugging Common JavaScript Mistakes

Oops, I did it again: Debugging Common JavaScript Mistakes

Sometimes writing JavaScript code is difficult, and sometimes it's just scary, which is familiar to many developers. In the process of work, errors inevitably occur, and some of them are often repeated. This article, aimed at beginner developers, talks about these errors and how to solve them. For clarity, the names of functions, properties and objects are taken from popular song. All this helps to quickly remember how to correct common mistakes.

We remind you: for all readers of "Habr" - a discount of 10 rubles when enrolling in any Skillbox course using the "Habr" promotional 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 example code above throws an Uncaught TypeError: Cannot read property 'lucky' of undefined. The problem is that the girl object does not have a named property, although it does have a name property. And since the girl.named property is not defined, it can't be accessed either, because it doesn't formally exist. But if you replace girl.named.lucky with girl.name, then everything will work and the program will return Lucky.

You can learn more about properties read here.

Ways to resolve TypeErrors

TypeErrors occur when a programmer attempts to perform actions on data that does not conform to a particular type. Examples include using .bold(), requesting an undefined property, or calling a function that isn't really a function.

So, if you try to call girl (), you will get an Uncaught TypeError: yourVariable.bold is not a function and girl is not a function, because the object is actually called, not the function.

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

Stack overflow

If you believe the authors of the words of the song Baby One More Time (this is Britney Spears, yeah), then the word hit in this context means the desire of the singer to be called again (here is an explanation of the very context of the song - translator's note). 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 recursion, which can cause an error if the call stack overflows.

The errors look like this:

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

A stack overflow occurs if the developer has not taken into account the base case in the recursion, or if the code does not address the provided case.

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

In this case, stillBelieve can never be false, so each time oneMoreTime will be called, but the function will never complete.

If you start relying on two friends, this will reduce loneliness (loneliness), and you can not wait for a call.

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

Examples include cases with infinite loops, when the system does not give an error message, and the page on which the JavaScript code is executed just 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 in the following way:

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

Debugging infinite loops and recursions

If you're having an infinite loop issue, close the tab in Chrome or Edge, and close the browser window in Firefox. After that, you need to carefully analyze the code. If you can't find the problem, it's worth adding a debugger command to a loop or function and checking the value of the variables. If the result is not as expected, then we replace it, this can be done easily.

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

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

Syntax error

One of the most common errors in JavaScript is the SyntaxError. Text editor extensions will help to avoid them. For example, Bracket Pair Colorizer marks the brackets in the code with different colors, and Prettier or a similar analysis tool makes it possible to quickly find errors. The best option to reduce the chance of getting a SyntaxError is to nest as little as possible.

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

Skillbox recommends:

Source: habr.com

Add a comment