JavaScript errors: fix, process, repair

Hello! Inspired by the success of the previous article, which was written ahead of the launch of the course "Fullstack JavaScript Developer", we decided to continue a series of articles for beginners and all those who are just starting to engage in programming in JavaScript. Today we will talk about errors that occur in JS, as well as how to deal with them.

Make one mistake for the person, and he will be grateful to you for one pull request. Teach him to debut on his own, and he will be grateful to you the whole project.

Unknown Timlid

Common Beginner Mistakes

So, let's start with the most primitive mistakes. Let's say you just recently finished learning the basics of HTML and CSS and are now actively embarking on JavaScript programming. For example: you want, when you click on a button, for example, you open a modal window hidden until this moment. Also, you want this window to close by clicking on the cross. An interactive example is available here (I chose bitbucket due to the fact that its interface seems to me the simplest, and it’s not all the same to sit on a github).

		let modal_alert = document.querySelector (". modal_alert")

let hero__btn = document.querySelector (". hero__btn")

let modal_close = document.querySelector (". modal-close")

// we selected our elements from the DOM model. By the way, I use bulma to simplify the layout process

// now we want to carry out some operations on our elements:


hero__btn.addEventListener ("click", function () {

    modal_alert.classList.add ("helper_visible");

})


modal_close.addEventListener ("click", function () {

    modal_alert.classList.remove ("helper_visible");

})

// if we want to see the form, then just hang up the add. the class in which the css property of display: flex is registered. And vice versa, if we want to hide.

IN index.html except layout inside the tag head we insert our script:

  

However, despite the fact that we all connected, nothing will work and an error will crash:

Which is very sad, newcomers are often lost and do not understand what to do with the red lines, as if this is some kind of verdict, and not a hint about what is wrong in your program. If translated, the browser tells us that it cannot read the property addEventListener zero value. So, for some reason, we did not get our element from the DOM model. What action algorithm should be taken?

First, look at what point you are being called javascript. The browser reads your html code from top to bottom, as you read, for example, a book. When he sees the tag script, it will immediately execute its contents and continue reading the following elements, not really caring that you are trying to get DOM elements in your script, but he has not read them yet and, therefore, has not built a model.

What to do in this case? Just add attribute defer inside your tag script (or async, but I will not go into details of their work now, it can be read here). Or you can just move your tag down script before closing body, this will work too.

Secondly, check typos. Learn the BEM methodology – it is also useful because you know how your element is written – after all, write classes according to the same logic, and try to use only the correct English language. Or copy the name of the element directly into the JS file.

Fine. Now that you have fixed the errors, you can enjoy the working version of the code at the following address.

Mysterious mistake

Most of all newcomers are confused by the strange mistake of the last line of code. Here is an example:

Something incomprehensible is displayed in the console. Translated, it’s literally “Unexpected end of input” – and what to do about it? In addition, the newcomer out of habit looks at the line number. Everything seems normal on her. And why then does the console point to it?

Everything is simple. To understand how to interpret your program, the JS interpreter needs to know where the body of the function ends and where the body of the loop ends. In this version of the code, I absolutely intentionally forgot the last brace:

		// here we just have two arrays with headings and articles

let root = document.getElementById ("root"); // react like using root

let article__btn = document.querySelector ("article__btn");

// when clicking on the button we read the article

article__btn.onclick = () => {

for (let i = 0; i <headers.length; i ++) {

root.insertAdjacentHTML ("beforeend", `

		

$ {headers[i]}

$ {paragraps[i]}

`) // curly brace removed by professionals. Do not repeat on production }

Now, JavaScript does not understand where it has the end of the function body, and where the end of the loop cannot interpret the code.

What to do in this case? In any modern code editor, if you place the cursor in front of the opening bracket, its closing option is highlighted (if the editor has not yet begun to underline this error in red). Review the code again carefully, keeping in mind that there are no lonesome braces in JS. You can see the problematic version here, and the corrected one – here.

Fragment the code

Most often it’s worth writing code, testing its work in small pieces. Or how can a normal person learn TDD For example, you need a simple program that receives input from the user, adds it to an array, and then displays their average values:

		let input_number = prompt ("Enter the number of variables");

// determine how many variables will come to us

let numbers = [];



function toArray (input_number) {

for (let i = 0; i <input_number; i ++) {

let x = prompt (`Enter the value of $ {i}`);

numbers.push (x); // and add the values ​​to an array

}

}

toArray (input_number);



function toAverage (numbers) {

let sum = 0;

for (let i = 0; i <numbers.length; i ++) {

sum + = numbers[i];

}

return sum / numbers.length;

}

alert (toAverage (numbers));

At first glance, everything is fine in this code. It has the basic logic, divided into two functions, each of which can then be applied separately. However, an experienced programmer will immediately say that it will not work, because from prompt data comes to us as a string. Moreover, JS (such is its tolerant and indifferent nature) will start everything for us, but at the output it will give out so incredible nonsense that it will even be difficult to understand how we got to such a life. So, let's try to count something in our interactive example. Let us introduce the number 3 in the number of variables, and 1 2 3 in the data entry field:

What? What? Okay, this is JavaScript. Let’s talk better, how could we avoid such a strange conclusion. It was necessary to write in Python, he would humanly warn us about an error. After each suspicious moment, we had to make a conclusion about the type of variables and look at the state of our array.

A variant of the code in which the probability of unexpected output is reduced:

		let input_number = prompt ("Enter the number of variables");



console.log (typeof (input_number));

let numbers = [];



function toArray (input_number) {

for (let i = 0; i <input_number; i ++) {

let x = prompt (`Enter the value of $ {i}`);

numbers.push (x);

}

}



toArray (input_number);

console.log (numbers);



function toAverage (numbers) {

let sum = 0;

for (let i = 0; i <numbers.length; i ++) {

sum + = numbers[i];

}

return sum / numbers.length;

}

console.log (typeof (toAverage (numbers)));

alert (toAverage (numbers));

In other words, I put all the suspicious places where something could go wrong in the console to make sure that everything is going as I expect. Of course the data console.log – children's toys and normal, of course, you need to study any decent library for testing. For example this one. The result of this debugging program can be seen in the developer tools here. How to fix it, I think, there will be no questions, but if it’s interesting, then here (and yes, this can be done simply with two pluses).

Step Up: Mastering Chrome Dev Tools

Debug using console.log in 2019, this is already a somewhat archaic thing (but we still will never forget it, it is already like our own). Every developer who wants to wear the proud title of a professional must master the rich tools of modern development tools.

Let's try to fix the problem areas in our code using Dev Tools. If you need documentation with examples, you can read everything here. And we will try to parse the previous example using Dev Tools.

So, we open an example. We obviously had some kind of bug hidden in the code, but how do you know at what point JavaScript started to read something incorrectly? That's right, we wrap this joy with tests for the type of a variable, it's very simple Go to the tab Sources in developer tools. Open file code.js. You will have 3 parts: the first on the left, which displays a list of files, and the second – in which we display the code. But most of the information we can get from the third part from below, which displays the progress of our code. Let's put breakpoint on line 15 (to do this, click on the line number in the window where we have the code displayed, after which you will see a blue mark). Restart the page and enter any values ​​in our program.

Now you can pull from the bottom panel debug a lot of useful information. You will find that JS is not really thinking about the type of variables because statistical languages ​​are stupidly better and you need to write only in them in order to get predictably working and fast programs adds the variables as a string to our array. Now, having realized the picture of what is happening, we can take countermeasures.

Learning to catch mistakes

Design try … catch found in all modern programming languages. Why is this syntax construct necessary? The fact is that when an error occurs in the code, it stops its execution at the place of the error – and the interpreter will not execute all further instructions. In a really working application, out of several hundred lines of code, this will not suit us. And suppose we want to intercept the error code, pass the code to the developer, and continue execution further.

Our article would be incomplete without a brief description of the main types of errors in JavaScript:

  • Error – The general constructor of the error object.
  • EvalError – type of error that appears during execution errors eval (), but not syntactic, but with the incorrect use of this global function.
  • Rangeerror – occurs when you go beyond the permissible range in the execution of your code.
  • ReferenceError – occurs when you try to call a variable, function or object that is not in the program.
  • Syntaxerrror – syntax error.
  • TypeError – occurs when trying to create an object with an unknown type of variable or when trying to call a nonexistent method
  • Urieror – rarely seen code that occurs when the encodeURL and DecodeURL methods are used incorrectly.

Great, let's practice a bit now and see in practice where we can use the design try … catch. The principle of operation of this construction is quite simple – the interpreter tries to execute the code inside tryif it turns out, then everything continues, as if this design never existed. But if an error occurred – we intercept it and can process it, for example, telling the user exactly where he missed.

Let's create the simplest calculator (even call it a calculator out loud, I would say: “executor of the entered expressions”). His interactive example can be found here. Ok, let's now look at our code:

		let input = document.querySelector ("# enter");

let button = document.querySelector ("# enter_button");

let result_el = document.querySelector ("# result");



button.onclick = () => {

try {

let result = eval (input.value); // try, if everything is correct, then catch will not work

result_el.innerHTML = result;

} catch (error) {

console.error (error.name);

result_el.innerHTML = "You entered something wrong, young man
Think again "; // you can explain to the user that he is wrong if he made a mistake // although naturally it is better for the user not to give this opportunity)) } }

If you try to enter the correct mathematical expression, then everything will work fine. However, try to enter an incorrect expression, for example, just a string, then the program will display a warning to the user.

I hope you read more articles explaining other parts of error trapping, such as this one, to broaden your understanding of program debugging, and explore other syntax constructs such as finallyas well as generating your own mistakes.

That's all. I hope this article was useful and now, when debugging applications, you will feel more confident. We analyzed typical errors from the most elementary that newcomers to JS programming make only a few days, to the error trapping technique used by more advanced developers.

And according to tradition, useful links:

  • We are writing our own testing framework. Useful for a general understanding of testing strategies.
  • Full documentation of errors, including experimental features
  • Incredibly useful article on MDN, which describes most of the problems that arise at the beginning of development on JS: debugging, polyfills, debugger and much more

That's all. We are waiting for your comments and invite you to free webinarwhere we talk about the possibilities SvelteJS framework.

Similar Posts

Leave a Reply

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