Oops, I did it again: debugging common errors in JavaScript

Oops, I did it again: debugging common errors in JavaScript

Sometimes writing JavaScript code can be challenging, and for many developers, it can even be intimidating. Throughout the development process, errors inevitably arise, and some of them tend to repeat frequently. This article is aimed at beginner developers and discusses these errors and their solutions. To illustrate, the names of functions, properties, and objects are taken from a popular song. All of this helps to quickly remember how to fix common mistakes.

Reminder: for all readers of 'Habr' - a discount of 10,000 rubles when enrolling in any Skillbox course with the promo code 'Habr'.

Skillbox recommends: Practical Course "Mobile Developer PRO".

TypeError: property is undefined

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 above code sample throws the error 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 undefined, it cannot be accessed, as it formally does not exist. However, if we replace girl.named.lucky with girl.name, everything will work and the program will return Lucky.

Learn more about properties read here.

Ways to fix TypeError errors

TypeError errors occur when a programmer attempts to perform actions with data that do not match a specified type. For example, this can happen when using .bold(), accessing an undefined property, or calling a function that is actually not a function.

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

To resolve errors, you need to study the variables. So, what is girl? And what is girl.named? You can find out by analyzing the code, outputting the variables using console.log, the debugger command, or by calling the variable name in the console. You need to ensure that you can operate with the data type contained in the variable. If it doesn't fit, modify it, for example, by adding a condition or using a try..catch block — and you will gain control over the execution of the operation.

Stack overflow

If we believe the authors of the song Baby One More Time (that's Britney Spears, yes), the word hit in this context means the singer's desire to be called again (this provides clarification about the song's context, — translator's note). It's quite possible that this desire will lead to an increased number of calls in real life. However, in programming, this refers to recursion, which can cause an error in case of a stack overflow.

Errors appear as follows:

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 did not account for the base case in recursion or if the code does not handle 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 be false, so oneMoreTime will be called every time, but the function will never complete.

If you start hoping for two friends, it will reduce loneliness, and the call may not be needed.

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

An example can be made with infinite loops, where the system does not provide an error message, and the page running the JavaScript simply hangs. 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")
}

The problem can be solved as follows:

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

Debugging Infinite Loops and Recursion

If there is a problem with an infinite loop, in Chrome or Edge, you need to close the tab, and in Firefox — the browser window. After that, carefully analyze the code. If you cannot find the problem, it's advisable to add the debugger command in the loop or function and check the values of the variables. If the result does not match what is expected, replace it, which can be easily done.

In the example mentioned above, the debugger should be added as the first line of a function or loop. Then, you need to open the debug tab in Chrome and analyze the variables in the scope. Using the next button allows you to track their changes during each iteration. It's all quite 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 SyntaxError. You can avoid them with text editor extensions. For example, Bracket Pair Colorizer highlights brackets in the code with different colors, while Prettier or a similar analysis tool allows you to quickly find errors. The best way to reduce the likelihood of encountering SyntaxError is minimal nesting.

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

Skillbox recommends:

Source: habr.com

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster