INTRODUCTION TO THE THEORY OF ERROR

      13

When you built up the "Guess the number" trò chơi in the previous article, you may have found that it didn"t work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to lớn find and fix errors in JavaScript programs.

Bạn đang xem: Introduction to the theory of error

Prerequisites: Objective:
Basic computer literacy, a basic understanding of HTML và CSS, an understanding of what JavaScript is.
lớn gain the ability và confidence khổng lồ start fixing problems in your own code.

Generally speaking, when you vì something wrong in code, there are two main types of error that you"ll come across:

Syntax errors: These are spelling errors in your code that actually cause the program not lớn run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay khổng lồ fix, as long as you are familiar with the right tools và know what the error messages mean! Logic errors: These are errors where the syntax is actually correct but the code is not what you intended it to lớn be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn"t an error message to direct you lớn the source of the error.

Okay, so it"s not quite that simple — there are some other differentiators as you drill down deeper. But the above classifications will vày at this early stage in your career. We"ll look at both of these types going forward.


To get started, let"s return lớn our number guessing trò chơi — except this time we"ll be exploring a version that has some deliberate errors introduced. Go lớn GitHub & make yourself a local copy of number-game-errors.html (see it running live here).

to get started, xuất hiện the local copy inside your favorite text editor, & your browser. Try playing the trò chơi — you"ll notice that when you press the "Submit guess" button, it doesn"t work!

Note: You might well have your own version of the game example that doesn"t work, which you might want khổng lồ fix! We"d still like you to lớn work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try khổng lồ fix your example.


At this point, let"s consult the greenlines.com.vn console khổng lồ see if it reports any syntax errors, then try to fix them. You"ll learn how below.


Earlier on in the course we got you khổng lồ type some simple JavaScript commands into the greenlines.com.vn tools JavaScript console (if you can"t remember how to xuất hiện this in your browser, follow the previous link to find out how). What"s even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser"s JavaScript engine. Now let"s go hunting.

Go to the tab that you"ve got number-game-errors.html xuất hiện in, and open your JavaScript console. You should see an error message along the following lines:
*
(number-game-errors.html:86:3)"." width="700" height="583" loading="lazy"> This is a pretty easy error to lớn track down, & the browser gives you several useful bits of information to help you out (the screenshot above is from Firefox, but other browsers provide similar information). From left to lớn right, we"ve got: A red "x" khổng lồ indicate that this is an error. An error message to indicate what"s gone wrong: "TypeError: guessSubmit.addeventListener is not a function" A "Learn More" link that links through lớn an MDN page that explains what this error means in greater detail. The name of the JavaScript file, which liên kết through to the Debugger tab of the greenlines.com.vn tools. If you follow this link, you"ll see the exact line where the error is highlighted. The line number where the error is, and the character number in that line where the error is first seen. In this case, we"ve got line 86, character number 3. If we look at line 86 in our code editor, we"ll find this line:

Warning: Error message may not be on line 86.

If you are using any code editor with an extension that launches a live vps on your local machine, this will cause extra code lớn be injected. Because of this, the greenlines.com.vn tools will menu the error as occurring on a line that is not 86.


So, looking at this page, the error appears to lớn be that we"ve spelled the function name wrong! Remember that JavaScript is case sensitive, so any slight difference in spelling or casing will cause an error. Changing addeventListener to addEventListener should fix this. Vày this now.
Save your page and refresh, and you should see the error has gone. Now if you try khổng lồ enter a guess & press the Submit guess button, you"ll see another error!
*
Have a look at line 78, và you"ll see the following code:
This line is trying to lớn set the textContent property of the lowOrHi constant to lớn a text string, but it"s not working because lowOrHi does not contain what it"s supposed to. Let"s see why this is — try searching for other instances of lowOrHi in the code. The earliest instance you"ll find in the JavaScript is on line 49:
Save và refresh, and you should now see the console.log() result in your console.
*
Sure enough, lowOrHi"s value is null at this point, so there is definitely a problem with line 49. So we need a class selector here, which begins with a dot (.), but the selector being passed into the querySelector() method in line 49 has no dot. This could be the problem! Try changing lowOrHi khổng lồ .lowOrHi in line 49. Try saving & refreshing again, và your console.log() statement should return the element we want. Phew! Another error fixed! You can delete your console.log() line now, or keep it to reference later on — your choice.
Now if you try playing the trò chơi through again, you should get more success — the game should play through absolutely fine, until you kết thúc the game, either by guessing the right number, or by running out of guesses. At that point, the trò chơi fails again, & the same error is spat out that we got at the beginning — "TypeError: resetButton.addeventListener is not a function"! However, this time it"s listed as coming from line 94. Looking at line number 94, it is easy to see that we"ve made the same mistake here. We again just need lớn change addeventListener lớn addEventListener. Vày this now.

Xem thêm: Cafe Giảm Cân Idol Slim Coffee Có Tốt Không, Rước Họa Vì Dùng Cà Phê Giảm Cân Ido Slim


At this point, the game should play through fine, however after playing through a few times you"ll undoubtedly notice that the "random" number you"ve got lớn guess is always 1. Definitely not quite how we want the trò chơi to play out!

There"s definitely a problem in the game lô ghích somewhere — the trò chơi is not returning an error; it just isn"t playing right.

tìm kiếm for the randomNumber variable, & the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the trò chơi should be around line number 45:

let randomNumber = Math.floor(Math.random()) + 1;
và the one that generates the random number before each subsequent game is around line 113:
randomNumber = Math.floor(Math.random()) + 1;
To check whether these lines are indeed the problem, let"s turn lớn our friend console.log() again — insert the following line directly below each of the above two lines:
Save and refresh, then play a few games — you"ll see that randomNumber is equal khổng lồ 1 at each point where it is logged lớn the console.
To fix this, let"s consider how this line is working. First, we invoke Math.random(), which generates a random decimal number between 0 & 1, e.g. 0.5675493843.


Next, we pass the result of invoking Math.random() through Math.floor(), which rounds the number passed lớn it down lớn the nearest whole number. We then địa chỉ 1 khổng lồ that result:


Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 lớn it will always return 1. We need khổng lồ multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:


Math.floor(Math.random() * 100);
Hence us wanting to add 1, lớn give us a random number between 1 và 100:


Math.floor(Math.random() * 100) + 1;
Try updating both lines like this, then save và refresh — the game should now play lượt thích we are intending it to!


There are other common errors you"ll come across in your code. This section highlights most of them.


This error generally means that you have missed a semicolon at the kết thúc of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the checkGuess() function:


const userGuess = Number(guessField.value);
to


const userGuess === Number(guessField.value);
It throws this error because it thinks you are trying to bởi something different. You should make sure that you don"t set up the assignment operator (=) — which sets a variable khổng lồ be equal to lớn a value — with the strict equality operator (===), which tests whether one value is equal lớn another, and returns a true/false result.


Note: See our SyntaxError: missing ; before statement reference page for more details about this error.


This could be another symptom of mixing up the assignment & strict equality operators. For example, if we were to change this line inside checkGuess():


if (userGuess === randomNumber) {
to


if (userGuess = randomNumber) {
the kiểm tra would always return true, causing the program to lớn report that the trò chơi has been won. Be careful!


This one is pretty simple — it generally means that you"ve missed the closing parenthesis at the over of a function/method call.


Note: See our SyntaxError: missing ) after argument list reference page for more details about this error.


This error usually relates lớn an incorrectly formed JavaScript object, but in this case we managed lớn get it by changing


function checkGuess() {
to


function checkGuess( {
This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!


This is easy — it generally means that you"ve missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the checkGuess() function.


These errors generally mean that you"ve left off a string value"s opening or closing quote mark. In the first error above, string would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.

For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go khổng lồ that line and see if you can spot what"s wrong. Bear in mind that the error is not necessarily going khổng lồ be on that line, and also that the error might not be caused by the exact same problem we cited above!


Note: See our SyntaxError: Unexpected token & SyntaxError: unterminated string literal reference pages for more details about these errors.


So there we have it, the basics of figuring out errors in simple JavaScript programs. It won"t always be that simple to work out what"s wrong in your code, but at least this will save you a few hours of sleep and allow you to lớn progress a bit faster when things don"t turn out right, especially in the earlier stages of your learning journey.