1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
---
title: Cosa è andato storto? Problemi con Javacript
slug: Learn/JavaScript/First_steps/What_went_wrong
translation_of: Learn/JavaScript/First_steps/What_went_wrong
original_slug: Learn/JavaScript/First_steps/Cosa_è_andato_storto
---
<div>{{LearnSidebar}}</div>
<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</div>
<p class="summary">Quando abbiamo realizzato il gioco "Indovina il numero" nell'articole precedente, potresti esserti accorto che non funziona. Niente paura — questo articolo mira ad aiutarti e non farti strappare i capelli per tali problemi, fornendoti alcuni semplici aiuti su come trovare e correggere gli errori in JavaScript .</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To gain the ability and confidence to start fixing simple problems in your own code.</td>
</tr>
</tbody>
</table>
<h2 id="Types_of_error">Types of error</h2>
<p>Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:</p>
<ul>
<li><strong>Syntax errors</strong>: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!</li>
<li><strong>Logic errors</strong>: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't a resulting error message to direct you to the source of the error.</li>
</ul>
<p>Okay, so it's not quite <em>that</em> simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.</p>
<h2 id="An_erroneous_example">An erroneous example</h2>
<p>To get started, let's return to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced. Go to Github and make yourself a local copy of <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">number-game-errors.html</a> (see it <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">running live here</a>).</p>
<ol>
<li>To get started, open the local copy inside your favourite text editor, and your browser.</li>
<li>Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!</li>
</ol>
<div class="note">
<p><strong>Note</strong>: You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to 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 to fix your example.</p>
</div>
<p>At this point, let's consult the developer console to see if we can see any syntax errors, then try to fix them. You'll learn how below.</p>
<h2 id="Fixing_syntax_errors">Fixing syntax errors</h2>
<p>Earlier on in the course we got you to type some simple JavaScript commands into the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a> (if you can't remember how to open 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.</p>
<ol>
<li>Go to the tab that you've got <code>number-game-errors.html</code> open in, and open your JavaScript console. You should see an error message along the following lines: <img alt="" src="https://mdn.mozillademos.org/files/13496/not-a-function.png" style="display: block; margin: 0 auto;"></li>
<li>This is a pretty easy error to track down, and 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 right, we've got:
<ul>
<li>A red "x" to indicate that this is an error.</li>
<li>An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function"</li>
<li>A "Learn More" link that links through to an MDN page that explains what this error means in huge amounts of detail.</li>
<li>The name of the JavaScript file, which links through to the Debugger tab of the devtools. If you follow this link, you'll see the exact line where the error is highlighted.</li>
<li>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.</li>
</ul>
</li>
<li>If we look at line 86 in our code editor, we'll find this line:
<pre class="brush: js">guessSubmit.addeventListener('click', checkGuess);</pre>
</li>
<li>The error message says "guessSubmit.addeventListener is not a function", so we've probably spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn <em>name-of-feature</em>" on your favourite search engine. Here's a shortcut to save you some time in this instance: <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>.</li>
<li>So, looking at this page, the error appears to 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 <code>addeventListener</code> to <code>addEventListener</code> should fix this. Do this now.</li>
</ol>
<div class="note">
<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function">TypeError: "x" is not a function</a> reference page for more details about this error.</p>
</div>
<h3 id="Syntax_errors_round_two">Syntax errors round two</h3>
<ol>
<li>Save your page and refresh, and you should see the error has gone.</li>
<li>Now if you try to enter a guess and press the Submit guess button, you'll see ... another error! <img alt="" src="https://mdn.mozillademos.org/files/13498/variable-is-null.png" style="display: block; margin: 0 auto;"></li>
<li>This time the error being reported is "TypeError: lowOrHi is null", on line 78.
<div class="note"><strong>Note</strong>: <code><a href="/en-US/docs/Glossary/Null">Null</a></code> is a special value that means "nothing", or "no value". So <code>lowOrHi</code> has been declared and initialised, but not with any meaningful value — it has no type or value.</div>
<div class="note"><strong>Note</strong>: This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the <code>checkGuess() { ... }</code> block). As you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the <code>checkGuess()</code> function was run by line 86.</div>
</li>
<li>Have a look at line 78, and you'll see the following code:
<pre class="brush: js">lowOrHi.textContent = 'Last guess was too high!';</pre>
</li>
<li>This line is trying to set the <code>textContent</code> property of the <code>lowOrHi</code> variable to a text string, but it's not working because <code>lowOrHi</code> does not contain what it's supposed to. Let's see why this is — try searching for other instances of <code>lowOrHi</code> in the code. The earliest instance you'll find in the JavaScript is on line 48:
<pre class="brush: js">var lowOrHi = document.querySelector('lowOrHi');</pre>
</li>
<li>At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's check whether the value is <code>null</code> after this line has been run. Add the following code on line 49:
<pre class="brush: js">console.log(lowOrHi);</pre>
<div class="note">
<p><strong>Note</strong>: <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code> is a really useful debugging function that prints a value to the console. So it will print the value of <code>lowOrHi</code> to the console as soon as we have tried to set it in line 48.</p>
</div>
</li>
<li>Save and refesh, and you should now see the <code>console.log()</code> result in your console. <img alt="" src="https://mdn.mozillademos.org/files/13494/console-log-output.png" style="display: block; margin: 0 auto;"> Sure enough, <code>lowOrHi</code>'s value is <code>null</code> at this point, so there is definitely a problem with line 48.</li>
<li>Let's think about what the problem could be. Line 48 is using a <code><a href="/en-US/docs/Web/API/Document/querySelector">document.querySelector()</a></code> method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question:
<pre class="brush: js"><p class="lowOrHi"></p></pre>
</li>
<li>So we need a class selector here, which begins with a dot (.), but the selector being passed into the <code>querySelector()</code> method in line 48 has no dot. This could be the problem! Try changing <code>lowOrHi</code> to <code>.lowOrHi</code> in line 48.</li>
<li>Try saving and refreshing again, and your <code>console.log()</code> statement should return the <code><p></code> element we want. Phew! Another error fixed! You can delete your <code>console.log()</code> line now, or keep it to reference later on — your choice.</li>
</ol>
<div class="note">
<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type">TypeError: "x" is (not) "y"</a> reference page for more details about this error.</p>
</div>
<h3 id="Syntax_errors_round_three">Syntax errors round three</h3>
<ol>
<li>Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of lives.</li>
<li>At that point, the game fails again, and 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.</li>
<li>Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change <code>addeventListener</code> to <code>.addEventListener</code>. Do this now.</li>
</ol>
<h2 id="A_logic_error">A logic error</h2>
<p>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 to guess is always 1. Definitely not quite how we want the game to play out!</p>
<p>There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.</p>
<ol>
<li>Search for the <code>randomNumber</code> variable, and 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 game should be around line number 44:
<pre class="brush: js">var randomNumber = Math.floor(Math.random()) + 1;</pre>
And the one that generates the random number before each subsequent game is around line 113:</li>
<li>
<pre class="brush: js">randomNumber = Math.floor(Math.random()) + 1;</pre>
</li>
<li>To check whether these lines are indeed the problem, let's turn to our friend <code>console.log()</code> again — insert the following line directly below each of the above two lines:
<pre class="brush: js">console.log(randomNumber);</pre>
</li>
<li>Save and refresh, then play a few games — you'll see that <code>randomNumber</code> is equal to 1 at each point where it is logged to the console.</li>
</ol>
<h3 id="Working_through_the_logic">Working through the logic</h3>
<p>To fix this, let's consider how this line is working. First, we invoke <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></code>, which generates a random decimal number between 0 and 1, e.g. 0.5675493843.</p>
<pre class="brush: js">Math.random()</pre>
<p>Next, we pass the result of invoking <code>Math.random()</code> through <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a></code>, which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:</p>
<pre>Math.floor(Math.random()) + 1</pre>
<p>Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:</p>
<pre class="brush: js">Math.floor(Math.random()*100);</pre>
<p>Hence us wanting to add 1, to give us a random number between 1 and 100:</p>
<pre class="brush: js">Math.floor(Math.random()*100) + 1;</pre>
<p>Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!</p>
<h2 id="Other_common_errors">Other common errors</h2>
<p>There are other common errors you'll come across in your code. This section highlights most of them.</p>
<h3 id="SyntaxError_missing_before_statement">SyntaxError: missing ; before statement</h3>
<p>This error generally means that you have missed a semi colon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the <code>checkGuess()</code> function:</p>
<pre class="brush: js">var userGuess = Number(guessField.value);</pre>
<p>to</p>
<pre class="brush: js">var userGuess === Number(guessField.value);</pre>
<p>It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (<code>=</code>) — which sets a variable to be equal to a value — with the strict equality operator (<code>===</code>), which tests whether one value is equal to another, and returns a <code>true</code>/<code>false</code> result.</p>
<div class="note">
<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement">SyntaxError: missing ; before statement</a> reference page for more details about this error.</p>
</div>
<h3 id="The_program_always_says_you've_won_regardless_of_the_guess_you_enter">The program always says you've won, regardless of the guess you enter</h3>
<p>This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside <code>checkGuess()</code>:</p>
<pre class="brush: js">if (userGuess === randomNumber) {</pre>
<p>to</p>
<pre class="brush: js">if (userGuess = randomNumber) {</pre>
<p>the test would always return <code>true</code>, causing the program to report that the game has been won. Be careful!</p>
<h3 id="SyntaxError_missing_)_after_argument_list">SyntaxError: missing ) after argument list</h3>
<p>This one is pretty simple — it generally means that you've missed the closing parenthesis off the end of a function/method call.</p>
<div class="note">
<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list">SyntaxError: missing ) after argument list</a> reference page for more details about this error.</p>
</div>
<h3 id="SyntaxError_missing_after_property_id">SyntaxError: missing : after property id</h3>
<p>This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing</p>
<pre class="brush: js">function checkGuess() {</pre>
<p>to</p>
<pre class="brush: js">function checkGuess( {</pre>
<p>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!</p>
<h3 id="SyntaxError_missing_after_function_body">SyntaxError: missing } after function body</h3>
<p>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 <code>checkGuess()</code> function.</p>
<h3 id="SyntaxError_expected_expression_got_'string'_or_SyntaxError_unterminated_string_literal">SyntaxError: expected expression, got '<em>string</em>' or SyntaxError: unterminated string literal</h3>
<p>These errors generally mean that you've missed off a string value's opening or closing quote mark. In the first error above, <em>string</em> 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.</p>
<p>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 to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!</p>
<div class="note">
<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token">SyntaxError: Unexpected token</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal">SyntaxError: unterminated string literal</a> reference pages for more details about these errors.</p>
</div>
<h2 id="Summary">Summary</h2>
<p>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 progress a bit faster when things don't turn out right earlier on in your learning journey.</p>
<h2 id="See_also">See also</h2>
<div>
<ul>
<li>There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail — see the <a href="/en-US/docs/Web/JavaScript/Reference/Errors">JavaScript error reference</a>.</li>
<li>If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask on the <a class="external external-icon" href="https://discourse.mozilla-community.org/t/learning-web-development-marking-guides-and-questions/16294">Learning Area Discourse thread</a>, or in the <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC channel on <a class="external external-icon" href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.</li>
</ul>
</div>
<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li>
</ul>
|