aboutsummaryrefslogtreecommitdiff
path: root/files/de/learn/javascript/first_steps/a_first_splash/index.html
blob: 6f5418d17b4b4dad969a31f0035555f5860386d7 (plain)
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
---
title: Ein erster Eindruck von JavaScript
slug: Learn/JavaScript/First_steps/A_first_splash
translation_of: Learn/JavaScript/First_steps/A_first_splash
original_slug: Learn/JavaScript/First_steps/Erster_Blick
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}</div>

<p class="summary">Nachdem Sie etwas über die Theorie von JavaScript gelernt haben und was Sie damit machen können, werden wir Ihnen in einem komplett praktischen Tutorial einen Crashkurs in den Grundfunktionen von JavaScript anbieten. Wir werden hier Schritt für Schritt ein einfaches Zahlenraten Spiel programmieren.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Voraussetzungen:</th>
   <td>Grundlegende Computerkenntnisse, einfache Grundkentnisse von HTML und CSS, sowie eine Vorstellung, was JavaScript ist.</td>
  </tr>
  <tr>
   <th scope="row">Ziel:</th>
   <td>Erste Erfahrung beim Schreiben von JavaScript zu bekommen und zumindest ein grundlegendes Verständnis dafür zu erlangen, was das Schreiben eines JavaScript-Programms beinhaltet.</td>
  </tr>
 </tbody>
</table>

<p>Es ist nicht nötig, dass Sie den gesamten Code sofort im Detail verstehen - wir wollen Ihnen nur grob die Konzepte vorab vorstellen und Ihnen eine Vorstellung davon vermitteln, wie JavaScript (und andere Programmiersprachen) funktionieren. In den folgenden Artikeln werden wir alle diese Funktionen noch einmal im Detail besprechen!</p>

<div class="note">
<p>Hinweis: Viele der Befehle und Konstrukte, die Sie in JavaScript sehen werden, sind die gleichen wie in anderen Programmiersprachen - Funktionen, Schleifen, etc. Die Syntax sieht anders aus, aber die Konzepte sind immer noch weitgehend die gleichen.</p>
</div>

<h2 id="Denken_wie_ein_Programmierer">Denken wie ein Programmierer</h2>

<p>Eines der schwierigsten Dinge, die man bei der Programmierung lernen muss, sind nicht die Befehle, sondern wie man sie zur Lösung der Aufgabe anwendet. Sie müssen anfangen, wie ein Programmierer zu denken - Sie müssen sich im klaren sein was  Ihr Programm tun soll, um dann herauszuarbeiten welche Funktionen und Befehle Sie dafür benötigen.</p>

<p>Dies erfordert eine Mischung aus harter Arbeit, Erfahrung mit der Programmiersprache und Praxis - und ein wenig Kreativität. Je mehr Sie kodieren, desto besser werden Sie werden. Wir können nicht versprechen, dass Sie in fünf Minuten ein "Programmierer-Gehirn" entwickeln werden, aber wir werden Ihnen viel Gelegenheit geben, während des gesamten Kurses das Denken wie ein Programmierer zu üben.</p>

<p>In diesem Sinne betrachten Sie das Beispiel, das wir in diesem Artikel erstellen werden und üben damit den Prozess der Zerlegung in konkrete Einzelschritte.</p>

<h2 id="Beispiel_—_Rate_die_Zahl">Beispiel — Rate die Zahl</h2>

<p>In diesem Artikel zeigen wir Ihnen, wie Sie das Ratespiel aufbauen können, das Sie hier sehen können.:</p>

<div class="hidden">
<h6 id="Top_hidden_code">Top hidden code</h6>

<pre class="brush: html">&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Number guessing game&lt;/title&gt;
    &lt;style&gt;
        html {
            font-family: sans-serif;
        }

        body {
            width: 50%;
            max-width: 800px;
            min-width: 480px;
            margin: 0 auto;
        }

        .lastResult {
            color: white;
            padding: 3px;
        }
    &lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;h1&gt;Zahlenraten&lt;/h1&gt;
    &lt;p&gt;Wir haben eine Zufallszahl zwischen 1 und 100 gewählt. Können Sie sie in höchstens 10 Versuchen erraten? Nach jeder Eingabe bekommen Sie einen Hinweis ob ihre Zahl zu gross oder zu klein war&lt;/p&gt;
    &lt;div class="form"&gt; &lt;label for="guessField"&gt;Geben Sie ihre Zahl ein: &lt;/label&gt;&lt;input type="text" id="guessField" class="guessField"&gt; &lt;input type="submit" value="Tip absenden" class="guessSubmit"&gt; &lt;/div&gt;
    &lt;div class="resultParas"&gt;
        &lt;p class="guesses"&gt;&lt;/p&gt;
        &lt;p class="lastResult"&gt;&lt;/p&gt;
        &lt;p class="lowOrHi"&gt;&lt;/p&gt;
    &lt;/div&gt;
&lt;script&gt;
    // Ihr JavaScript Code steht hier
    let randomNumber = Math.floor(Math.random() * 100) + 1;
    const guesses = document.querySelector('.guesses');
    const lastResult = document.querySelector('.lastResult');
    const lowOrHi = document.querySelector('.lowOrHi');
    const guessSubmit = document.querySelector('.guessSubmit');
    const guessField = document.querySelector('.guessField');
    let guessCount = 1;
    let resetButton;

    function checkGuess() {
      let userGuess = Number(guessField.value);
      if (guessCount === 1) {
        guesses.textContent = 'Vorherige Versuche: ';
      }

      guesses.textContent += userGuess + ' ';

      if (userGuess === randomNumber) {
        lastResult.textContent = 'Glückwunsch! Richtig geraten!';
        lastResult.style.backgroundColor = 'green';
        lowOrHi.textContent = '';
        setGameOver();
      } else if (guessCount === 10) {
        lastResult.textContent = '!!!ENDESPIEL!!!';
        lowOrHi.textContent = '';
        setGameOver();
      } else {
        lastResult.textContent = 'Falsch!';
        lastResult.style.backgroundColor = 'red';
        if(userGuess &lt; randomNumber) {
          lowOrHi.textContent = 'Ihre Zahl ist zu niedrig!' ;
        } else if(userGuess &gt; randomNumber) {
          lowOrHi.textContent = 'Ihre Zahl ist zu hoch!';
        }
      }

      guessCount++;
      guessField.value = '';
    }

    guessSubmit.addEventListener('click', checkGuess);

    function setGameOver() {
      guessField.disabled = true;
      guessSubmit.disabled = true;
      resetButton = document.createElement('button');
      resetButton.textContent = 'Spiel neu starten';
      document.body.appendChild(resetButton);
      resetButton.addEventListener('click', resetGame);
    }

    function resetGame() {
      guessCount = 1;
      const resetParas = document.querySelectorAll('.resultParas p');
      for(let i = 0 ; i &lt; resetParas.length ; i++) {
        resetParas[i].textContent = '';
      }

      resetButton.parentNode.removeChild(resetButton);
      guessField.disabled = false;
      guessSubmit.disabled = false;
      guessField.value = '';
      guessField.focus();
      lastResult.style.backgroundColor = 'white';
      randomNumber = Math.floor(Math.random() * 100) + 1;
    }
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}</p>

<p>Machen Sie sich mit der Funktionsweise des Spiels vertraut, bevor Sie weitermachen.</p>

<p>Stellen wir uns vor, Ihr Chef hat Ihnen den folgenden Auftrag für die Erstellung dieses Spiels gegeben:</p>

<blockquote>
<p>Schreiben Sie ein Programm das ein Zahlenratespiel implementiert. Es sollte eine Zufallszahl zwischen 1 und 100 wählen und den Spieler auffordern, die Zahl nach spätestens 10 Runden zu erraten. Nach jedem Zug sollte dem Spieler mitgeteilt werden, ob er richtig geraten hat oder nicht - und, wenn er Unrecht hat, ob die Zahl zu niedrig oder zu hoch war. Außerdem sollen dem Spieler alle vorher geratenen Zahlen angezeigt werden. Das Spiel endet, wenn der Spieler richtig rät oder wenn er 10-mal falsch geraten hat. Wenn das Spiel endet, sollte dem Spieler die Möglichkeit gegeben werden, erneut zu spielen.</p>
</blockquote>

<p>Wenn wir uns diesen Anweisungen ansehen, können wir zunächst damit beginnen, ihn in einfache, umsetzbare Aufgaben aufzuteilen, und zwar aus der Sicht eines Programmierers:</p>

<ol>
 <li>Generiere eine zufällige Zahl zwischen 1 und 100.</li>
 <li>Speichere die Anzahl der getätigten Rateversuche, setze den Wert anfangs auf 1.</li>
 <li>Ermögliche dem Spieler, einen Tipp abzugeben.</li>
 <li>Sobald ein Tip abgegeben wurde, speichere sie damit der Spieler seine vorherigen Eingaben sehen kann.</li>
 <li>Als Nächstes überprüfe, ob es sich um die richtige Zahl handelt.</li>
 <li>Wenn sie richtig ist:
  <ol>
   <li>Zeige Glückwunsch Nachricht.</li>
   <li>Verhindere weiter Eingaben, da das Spiel zu Ende ist.</li>
   <li>Biete eine Möglichkeit, das Spiel neu zu starten.</li>
  </ol>
 </li>
 <li>Wenn sie falsch ist und noch Versuche übrig sind:
  <ol>
   <li>Dem Spieler mitteilen, dass die Zahl noch nicht erraten ist.</li>
   <li>Die Eingabe einer weiteren Zahl ermöglichen.</li>
   <li>Die Anzahl der Rateversuche um 1 erhöhen.</li>
  </ol>
 </li>
 <li>Wenn die Zahl falsch ist und keine Versuche mehr übrig sind:
  <ol>
   <li>Dem Spieler mitteilen, dass das Spiel zu Ende ist.</li>
   <li>Keine weiteren Eingaben mehr zulassen.</li>
   <li>Ein Steuerelement zum Neustart des Spiels anzeigen.</li>
  </ol>
 </li>
 <li>Wenn das Spiel neu startet, sicherstellen dass Logik und Benutzeroberfläche zurückgesetzt werden. Danach zurück zum 1. Schritt.</li>
</ol>

<p>Lassen Sie uns nun fortfahren und schauen, wie wir diese Punkte in Code umwandeln können, das Beispiel aufbauen und die JavaScript-Funktionen während der Arbeit erforschen.</p>

<h3 id="Vorbereitungen">Vorbereitungen</h3>

<p>Um dieses Tutorial zu beginnen, möchten wir Sie bitten, eine lokale Kopie der Datei <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html">number-guessing-game-start.html</a> (<a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game-start.html">see it live here</a>) zu erstellen. Öffnen Sie es sowohl in Ihrem Texteditor als auch in Ihrem Webbrowser. Im Moment sehen Sie eine einfache Überschrift, einen Absatz mit Anweisungen und ein Formular zur Eingabe einer Schätzung, aber das Formular wird derzeit nichts tun.</p>

<p>Unseren gesamten Code werden wir innerhalb des {{htmlelement("script")}} Elements am Ende der HTML-Datei einfügen:</p>

<pre class="brush: html">&lt;script&gt;

  // Ihr Programm steht hier

&lt;/script&gt;
</pre>

<h3 id="Variablen_hinzufügen_um_Daten_zu_speichern">Variablen hinzufügen um Daten zu speichern</h3>

<p>Lassen Sie uns anfangen. Fügen Sie zunächst die folgenden Zeilen nach dem {{htmlelement("script")}} Element ein:</p>

<pre class="brush: js">let randomNumber = Math.floor(Math.random() * 100) + 1;

const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');

const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');

let guessCount = 1;
let resetButton;</pre>

<p>Obiger Code richtet die Variablen und Konstanten ein, die wir benötigen, um die Daten zu speichern, die unser Programm verwenden wird. Variablen sind im Grunde genommen Container für Werte (z.B. Zahlen oder Text). Sie erstellen eine Variable mit dem Schlüsselwort <code>let</code> (oder <code>var</code>) gefolgt von einem Namen für Ihre Variable (Sie werden mehr über den Unterschied zwischen den beiden Schlüsselwörtern in einem zukünftigen Artikel lesen). Konstanten werden verwendet, um Werte zu speichern, die Sie nicht ändern möchten, und werden mit dem Schlüsselwort const erstellt. In diesem Fall verwenden wir Konstanten, um Referenzen auf Teile unserer Benutzeroberfläche zu speichern; der Text in einigen von ihnen kann sich ändern, aber die referenzierten HTML-Elemente bleiben unverändert.</p>

<p>Sie können Ihrer Variablen oder Konstanten einen Wert mit einem Gleichheitszeichen (=) zuweisen, gefolgt von dem Wert, den Sie ihr geben möchten.</p>

<p>In unser Beispiel:</p>

<ul>
 <li>Die erste Variable — <code>randomNumber</code> — ist assigned a random number between 1 and 100, calculated using a mathematical algorithm.</li>
 <li>The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code:
  <pre class="brush: html">&lt;p class="guesses"&gt;&lt;/p&gt;
&lt;p class="lastResult"&gt;&lt;/p&gt;
&lt;p class="lowOrHi"&gt;&lt;/p&gt;</pre>
 </li>
 <li>The next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
  <pre class="brush: html">&lt;label for="guessField"&gt;Enter a guess: &lt;/label&gt;&lt;input type="text" id="guessField" class="guessField"&gt;
&lt;input type="submit" value="Submit guess" class="guessSubmit"&gt;</pre>
 </li>
 <li>Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).</li>
</ul>

<div class="note">
<p><strong>Note</strong>: You'll learn a lot more about variables/constants later on in the course, starting with the <a href="https://developer.mozilla.org/en-US/docs/user:chrisdavidmills/variables">next article</a>.</p>
</div>

<h3 id="Functions">Functions</h3>

<p>Next, add the following below your previous JavaScript:</p>

<pre class="brush: js">function checkGuess() {
  alert('I am a placeholder');
}</pre>

<p>Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword <code>function</code>, followed by a name, with parentheses put after it. After that we put two curly braces (<code>{ }</code>). Inside the curly braces goes all the code that we want to run whenever we call the function.</p>

<p>When we want to run the code, we type the name of the function followed by the parentheses.</p>

<p>Let's try that now. Save your code and refresh the page in your browser. Then go into the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>, and enter the following line:</p>

<pre class="brush: js">checkGuess();</pre>

<p>After pressing <kbd>Return</kbd>/<kbd>Enter</kbd>, you should see an alert come up that says "<samp>I am a placeholder</samp>"; we have defined a function in our code that creates an alert whenever we call it.</p>

<div class="note">
<p><strong>Note</strong>: You'll learn a lot more about functions <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Functions">later in the course</a>.</p>
</div>

<h3 id="Operators">Operators</h3>

<p>JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.</p>

<p>If you haven't already done so, save your code, refresh the page in your browser, and open the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a>. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing <kbd>Return</kbd>/<kbd>Enter</kbd> after each one, and see what results they return.</p>

<p>First let's look at arithmetic operators, for example:</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Operator</th>
   <th scope="col">Name</th>
   <th scope="col">Example</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>+</code></td>
   <td>Addition</td>
   <td><code>6 + 9</code></td>
  </tr>
  <tr>
   <td><code>-</code></td>
   <td>Subtraction</td>
   <td><code>20 - 15</code></td>
  </tr>
  <tr>
   <td><code>*</code></td>
   <td>Multiplication</td>
   <td><code>3 * 7</code></td>
  </tr>
  <tr>
   <td><code>/</code></td>
   <td>Division</td>
   <td><code>10 / 5</code></td>
  </tr>
 </tbody>
</table>

<p>You can also use the <code>+</code> operator to join text strings together (in programming, this is called <em>concatenation</em>). Try entering the following lines, one at a time:</p>

<pre class="brush: js">let name = 'Bingo';
name;
let hello = ' says hello!';
hello;
let greeting = name + hello;
greeting;</pre>

<p>There are also some shortcut operators available, called augmented <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">assignment operators</a>. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:</p>

<pre class="brush: js">name += ' says hello!';</pre>

<p>This is equivalent to</p>

<pre class="brush: js">name = name + ' says hello!';</pre>

<p>When we are running true/false tests (for example inside conditionals — see {{anch("Conditionals", "below")}}) we use <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">comparison operators</a>. For example:</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Operator</th>
   <th scope="col">Name</th>
   <th scope="col">Example</th>
  </tr>
  <tr>
   <td><code>===</code></td>
   <td>Strict equality (is it exactly the same?)</td>
   <td>
    <pre class="brush: js">
5 === 2 + 4 // false
'Chris' === 'Bob' // false
5 === 2 + 3 // true
2 === '2' // false; number versus string
</pre>
   </td>
  </tr>
  <tr>
   <td><code>!==</code></td>
   <td>Non-equality (is it not the same?)</td>
   <td>
    <pre class="brush: js">
5 !== 2 + 4 // true
'Chris' !== 'Bob' // true
5 !== 2 + 3 // false
2 !== '2' // true; number versus string
</pre>
   </td>
  </tr>
  <tr>
   <td><code>&lt;</code></td>
   <td>Less than</td>
   <td>
    <pre class="brush: js">
6 &lt; 10 // true
20 &lt; 10 // false</pre>
   </td>
  </tr>
  <tr>
   <td><code>&gt;</code></td>
   <td>Greater than</td>
   <td>
    <pre class="brush: js">
6 &gt; 10 // false
20 &gt; 10  // true</pre>
   </td>
  </tr>
 </thead>
</table>

<h3 id="Conditionals">Conditionals</h3>

<p>Returning to our <code>checkGuess()</code> function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.</p>

<p>At this point, replace your current <code>checkGuess()</code> function with this version instead:</p>

<pre class="brush: js">function checkGuess() {
  let userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = 'Previous guesses: ';
  }
  guesses.textContent += userGuess + ' ';

  if (userGuess === randomNumber) {
    lastResult.textContent = 'Congratulations! You got it right!';
    lastResult.style.backgroundColor = 'green';
    lowOrHi.textContent = '';
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = '!!!GAME OVER!!!';
    setGameOver();
  } else {
    lastResult.textContent = 'Wrong!';
    lastResult.style.backgroundColor = 'red';
    if(userGuess &lt; randomNumber) {
      lowOrHi.textContent = 'Last guess was too low!';
    } else if(userGuess &gt; randomNumber) {
      lowOrHi.textContent = 'Last guess was too high!';
    }
  }

  guessCount++;
  guessField.value = '';
  guessField.focus();
}</pre>

<p>This is a lot of code — phew! Let's go through each section and explain what it does.</p>

<ul>
 <li>The first line (line 2 above) declares a variable called <code>userGuess</code> and sets its value to the current value entered inside the text field. We also run this value through the built-in <code>Number()</code> constructor, just to make sure the value is definitely a number.</li>
 <li>Next, we encounter our first conditional code block (lines 3–5 above). A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword <code>if</code>, then some parentheses, then some curly braces. Inside the parentheses we include a test. If the test returns <code>true</code>, we run the code inside the curly braces. If not, we don't, and move on to the next bit of code. In this case the test is testing whether the <code>guessCount</code> variable is equal to <code>1</code> (i.e. whether this is the player's first go or not):
  <pre class="brush: js">guessCount === 1</pre>
  If it is, we make the guesses paragraph's text content equal to "<samp>Previous guesses: </samp>". If not, we don't.</li>
 <li>Line 6 appends the current <code>userGuess</code> value onto the end of the <code>guesses</code> paragraph, plus a blank space so there will be a space between each guess shown.</li>
 <li>The next block (lines 8–24 above) does a few checks:
  <ul>
   <li>The first <code>if(){ }</code> checks whether the user's guess is equal to the <code>randomNumber</code> set at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called <code>setGameOver()</code>, which we'll discuss later.</li>
   <li>Now we've chained another test onto the end of the last one using an <code>else if(){ }</code> structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.</li>
   <li>The final block chained onto the end of this code (the <code>else { }</code>) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.</li>
  </ul>
 </li>
 <li>The last three lines in the function (lines 26–28 above) get us ready for the next guess to be submitted. We add 1 to the <code>guessCount</code> variable so the player uses up their turn (<code>++</code> is an incrementation operation — increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.</li>
</ul>

<h3 id="Events">Events</h3>

<p>At this point we have a nicely implemented <code>checkGuess()</code> function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called <strong>event listeners</strong>, and the blocks of code that run in response to the event firing are called <strong>event handlers</strong>.</p>

<p>Add the following line below your <code>checkGuess()</code> function:</p>

<pre class="brush: js">guessSubmit.addEventListener('click', checkGuess);</pre>

<p>Here we are adding an event listener to the <code>guessSubmit</code> button. This is a method that takes two input values (called <em>arguments</em>) — the type of event we are listening out for (in this case <code>click</code>) as a string, and the code we want to run when the event occurs (in this case the <code>checkGuess()</code> function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.</p>

<p>Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the <code>setGameOver()</code> function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.</p>

<h3 id="Finishing_the_game_functionality">Finishing the game functionality</h3>

<p>Let's add that <code>setGameOver()</code> function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:</p>

<pre class="brush: js">function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement('button');
  resetButton.textContent = 'Start new game';
  document.body.appendChild(resetButton);
  resetButton.addEventListener('click', resetGame);
}</pre>

<ul>
 <li>The first two lines disable the form text input and button by setting their disabled properties to <code>true</code>. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.</li>
 <li>The next three lines generate a new {{htmlelement("button")}} element, set its text label to "Start new game", and add it to the bottom of our existing HTML.</li>
 <li>The final line sets an event listener on our new button so that when it is clicked, a function called <code>resetGame()</code> is run.</li>
</ul>

<p>Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:</p>

<pre class="brush: js">function resetGame() {
  guessCount = 1;

  const resetParas = document.querySelectorAll('.resultParas p');
  for (let i = 0 ; i &lt; resetParas.length ; i++) {
    resetParas[i].textContent = '';
  }

  resetButton.parentNode.removeChild(resetButton);

  guessField.disabled = false;
  guessSubmit.disabled = false;
  guessField.value = '';
  guessField.focus();

  lastResult.style.backgroundColor = 'white';

  randomNumber = Math.floor(Math.random() * 100) + 1;
}</pre>

<p>This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:</p>

<ul>
 <li>Puts the <code>guessCount</code> back down to 1.</li>
 <li>Empties all the text out of the information paragraphs.</li>
 <li>Removes the reset button from our code.</li>
 <li>Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.</li>
 <li>Removes the background color from the <code>lastResult</code> paragraph.</li>
 <li>Generates a new random number so that you are not just guessing the same number again!</li>
</ul>

<p><strong>At this point you should have a fully working (simple) game — congratulations!</strong></p>

<p>All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.</p>

<h3 id="Loops">Loops</h3>

<p>One part of the above code that we need to take a more detailed look at is the <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a> loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.</p>

<p>To start with, go to your <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer tools JavaScript console</a> again, and enter the following:</p>

<pre class="brush: js">for (let i = 1 ; i &lt; 21 ; i++) { console.log(i) }</pre>

<p>What happened? The numbers <samp>1</samp> to <samp>20</samp> were printed out in your console. This is because of the loop. A <code>for</code> loop takes three input values (arguments):</p>

<ol>
 <li><strong>A starting value</strong>: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter <code>i</code> with any name you like too, but <code>i</code> is used as a convention because it's short and easy to remember.</li>
 <li><strong>An exit condition</strong>: Here we have specified <code>i &lt; 21</code> — the loop will keep going until <code>i</code> is no longer less than 21. When <code>i</code> reaches 21, the loop will no longer run.</li>
 <li><strong>An incrementor</strong>: We have specified <code>i++</code>, which means "add 1 to i". The loop will run once for every value of <code>i</code>, until <code>i</code> reaches a value of 21 (as discussed above). In this case, we are simply printing the value of <code>i</code> out to the console on every iteration using {{domxref("Console.log", "console.log()")}}.</li>
</ol>

<p>Now let's look at the loop in our number guessing game — the following can be found inside the <code>resetGame()</code> function:</p>

<pre class="brush: js">let resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i &lt; resetParas.length ; i++) {
  resetParas[i].textContent = '';
}</pre>

<p>This code creates a variable containing a list of all the paragraphs inside <code>&lt;div class="resultParas"&gt;</code> using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.</p>

<h3 id="A_small_discussion_on_objects">A small discussion on objects</h3>

<p>Let's add one more final improvement before we get to this discussion. Add the following line just below the <code>let resetButton;</code> line near the top of your JavaScript, then save your file:</p>

<pre class="brush: js">guessField.focus();</pre>

<p>This line uses the {{domxref("HTMLElement.focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.</p>

<p>Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.</p>

<p>In this particular case, we first created a <code>guessField</code> constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:</p>

<pre class="brush: js">const guessField = document.querySelector('.guessField');</pre>

<p>To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. <code>querySelector()</code> takes one piece of information — a <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors">CSS selector</a> that selects the element you want a reference to.</p>

<p>Because <code>guessField</code> now contains a reference to an {{htmlelement("input")}} element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is <code>focus()</code>, so we can now use this line to focus the text input:</p>

<pre class="brush: js">guessField.focus();</pre>

<p>Variables that don't contain references to form elements won't have <code>focus()</code> available to them. For example, the <code>guesses</code> constant contains a reference to a {{htmlelement("p")}} element, and the <code>guessCount</code> variable contains a number.</p>

<h3 id="Playing_with_browser_objects">Playing with browser objects</h3>

<p>Let's play with some browser objects a bit.</p>

<ol>
 <li>First of all, open up your program in a browser.</li>
 <li>Next, open your <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">browser developer tools</a>, and make sure the JavaScript console tab is open.</li>
 <li>Type in <code>guessField</code> and the console will show you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!</li>
 <li>Now type in the following:
  <pre class="brush: js">guessField.value = 'Hello';</pre>
  The <code>value</code> property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!</li>
 <li>Now try typing in <code>guesses</code> and pressing return. The console will show you that the variable contains a {{htmlelement("p")}} element.</li>
 <li>Now try entering the following line:
  <pre class="brush: js">guesses.value</pre>
  The browser will return <code>undefined</code>, because paragraphs don't have the <code>value</code> property.</li>
 <li>To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this:
  <pre class="brush: js">guesses.textContent = 'Where is my paragraph?';</pre>
 </li>
 <li>Now for some fun stuff. Try entering the below lines, one by one:
  <pre class="brush: js">guesses.style.backgroundColor = 'yellow';
guesses.style.fontSize = '200%';
guesses.style.padding = '10px';
guesses.style.boxShadow = '3px 3px 6px black';</pre>
  Every element on a page has a <code>style</code> property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.</li>
</ol>

<h2 id="Finished_for_now...">Finished for now...</h2>

<p>So that's it for building the example. You got to the end — well done! Try your final code out, or <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">play with our finished version here</a>. If you can't get the example to work, check it against the <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html">source code</a>.</p>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "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>