aboutsummaryrefslogtreecommitdiff
path: root/files/tr/learn/javascript/first_steps/a_first_splash/index.html
blob: 8cab0bbcf256031c2a8016ec80e39c82cd7e38f5 (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
599
600
---
title: Javascript'e ilk giriş
slug: Öğren/JavaScript/First_steps/Javascripte_giris
translation_of: Learn/JavaScript/First_steps/A_first_splash
---
<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">Artık JavaScript teorisi ve onunla neler yapabileceğiniz hakkında bir şeyler öğrendiniz, tamamen pratik bir öğretici aracılığıyla size JavaScript'in temel özellikleri hakkında hızlandırılmış bir kurs vereceğiz. Burada adım adım basit bir "Sayıyı tahmin et" oyunu oluşturacaksınız.</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 have a first bit of experience at writing some JavaScript, and gain at least a basic understanding of what writing a JavaScript program involves.</td>
  </tr>
 </tbody>
</table>

<p>You won't be expected to understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how JavaScript (and other programming languages) work. In subsequent articles, you'll revisit all these features in a lot more detail!</p>

<div class="note">
<p>Note: Many of the code features you'll see in JavaScript are the same as in other programming languages — functions, loops, etc. The code syntax looks different, but the concepts are still largely the same.</p>
</div>

<h2 id="Thinking_like_a_programmer">Thinking like a programmer</h2>

<p>One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. You need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together.</p>

<p>This requires a mixture of hard work, experience with the programming syntax, and practice — plus a bit of creativity. The more you code, the better you'll get at it. We can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a programmer throughout the course.</p>

<p>With that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.</p>

<h2 id="Example_—_Guess_the_number_game">Example — Guess the number game</h2>

<p>In this article we'll show you how to build up the simple game you can see below:</p>

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

<pre class="brush: html notranslate">&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;Number guessing game&lt;/h1&gt;
    &lt;p&gt;We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.&lt;/p&gt;
    &lt;div class="form"&gt; &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; &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;
    // Your JavaScript goes here
    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 = '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!!!';
        lowOrHi.textContent = '';
        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 = '';
    }

    guessSubmit.addEventListener('click', checkGuess);

    function setGameOver() {
      guessField.disabled = true;
      guessSubmit.disabled = true;
      resetButton = document.createElement('button');
      resetButton.textContent = 'Start new game';
      document.body.append(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>Have a go at playing it — familiarize yourself with the game before you move on.</p>

<p>Let's imagine your boss has given you the following brief for creating this game:</p>

<blockquote>
<p>I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.</p>
</blockquote>

<p>Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:</p>

<ol>
 <li>Generate a random number between 1 and 100.</li>
 <li>Record the turn number the player is on. Start it on 1.</li>
 <li>Provide the player with a way to guess what the number is.</li>
 <li>Once a guess has been submitted first record it somewhere so the user can see their previous guesses.</li>
 <li>Next, check whether it is the correct number.</li>
 <li>If it is correct:
  <ol>
   <li>Display congratulations message.</li>
   <li>Stop the player from being able to enter more guesses (this would mess the game up).</li>
   <li>Display control allowing the player to restart the game.</li>
  </ol>
 </li>
 <li>If it is wrong and the player has turns left:
  <ol>
   <li>Tell the player they are wrong.</li>
   <li>Allow them to enter another guess.</li>
   <li>Increment the turn number by 1.</li>
  </ol>
 </li>
 <li>If it is wrong and the player has no turns left:
  <ol>
   <li>Tell the player it is game over.</li>
   <li>Stop the player from being able to enter more guesses (this would mess the game up).</li>
   <li>Display control allowing the player to restart the game.</li>
  </ol>
 </li>
 <li>Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.</li>
</ol>

<p>Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.</p>

<h3 id="Initial_setup">Initial setup</h3>

<p>To begin this tutorial, we'd like you to make a local copy of the <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> file (<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>). Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.</p>

<p>The place where we'll be adding all our code is inside the {{htmlelement("script")}} element at the bottom of the HTML:</p>

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

  // Your JavaScript goes here

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

<h3 id="Adding_variables_to_store_our_data">Adding variables to store our data</h3>

<p>Let's get started. First of all, add the following lines inside your {{htmlelement("script")}} element:</p>

<pre class="brush: js notranslate">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>This section of the code sets up the variables and constants we need to store the data our program will use. Variables are basically containers for values (such as numbers, or strings of text). You create a variable with the keyword <code>let</code> (or <code>var</code>) followed by a name for your variable (you'll read more about the difference between the keywords in a <a href="/en-US/docs/Learn/JavaScript/First_steps/Variables#The_difference_between_var_and_let">future article</a>). Constants are used to store values that are immutable or can't be changed and are created with the keyword <code>const</code>. In this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the HTML elements referenced stay the same.</p>

<p>You can assign a value to your variable or constant with an equals sign (<code>=</code>) followed by the value you want to give it.</p>

<p>In our example:</p>

<ul>
 <li>The first variable — <code>randomNumber</code> — is 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 (note how they are inside a <code>&lt;div&gt;</code> element, which is itself used to select all three later on for resetting, when we restart the game):
  <pre class="brush: html notranslate">&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;
</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 notranslate">&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 notranslate">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 notranslate">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 math, 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 notranslate">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 notranslate">name += ' says hello!';</pre>

<p>This is equivalent to</p>

<pre class="brush: js notranslate">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 notranslate">
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 notranslate">
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 notranslate">
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 notranslate">
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 notranslate">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 notranslate">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 <strong>event</strong>. 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 notranslate">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 notranslate">function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement('button');
  resetButton.textContent = 'Start new game';
  document.body.append(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 notranslate">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. We select all paragraphs inside <code>&lt;div class="resultParas"&gt;&lt;/div&gt;</code>, then loop through each one, setting their <code>textContent</code> to <code>''</code> (an empty string).</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 notranslate">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>A 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 notranslate">const 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 notranslate">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, most of the items you will manipulate in your code are objects. 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 notranslate">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 now has 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 notranslate">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 <code>guessField</code> into the console and the console shows 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 notranslate">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 <code>guesses</code> into the console and pressing return. The console shows you that the variable contains a {{htmlelement("p")}} element.</li>
 <li>Now try entering the following line:
  <pre class="brush: js notranslate">guesses.value</pre>
  The browser returns <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 notranslate">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 notranslate">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>