From 30feb96f6084a2fb976a24ac01c1f4a054611b62 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:47:54 +0100 Subject: unslug it: move --- .../cosa_\303\250_andato_storto/index.html" | 253 ---------------- .../javascript/first_steps/variabili/index.html | 337 --------------------- .../javascript/first_steps/variables/index.html | 337 +++++++++++++++++++++ .../first_steps/what_went_wrong/index.html | 253 ++++++++++++++++ 4 files changed, 590 insertions(+), 590 deletions(-) delete mode 100644 "files/it/learn/javascript/first_steps/cosa_\303\250_andato_storto/index.html" delete mode 100644 files/it/learn/javascript/first_steps/variabili/index.html create mode 100644 files/it/learn/javascript/first_steps/variables/index.html create mode 100644 files/it/learn/javascript/first_steps/what_went_wrong/index.html (limited to 'files/it/learn/javascript/first_steps') diff --git "a/files/it/learn/javascript/first_steps/cosa_\303\250_andato_storto/index.html" "b/files/it/learn/javascript/first_steps/cosa_\303\250_andato_storto/index.html" deleted file mode 100644 index 1fa4343de8..0000000000 --- "a/files/it/learn/javascript/first_steps/cosa_\303\250_andato_storto/index.html" +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Cosa è andato storto? Problemi con Javacript -slug: Learn/JavaScript/First_steps/Cosa_è_andato_storto -translation_of: Learn/JavaScript/First_steps/What_went_wrong ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}
- -

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 .

- - - - - - - - - - - - -
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective:To gain the ability and confidence to start fixing simple problems in your own code.
- -

Types of error

- -

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

- - - -

Okay, so it's not quite that 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.

- -

An erroneous example

- -

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 number-game-errors.html (see it running live here).

- -
    -
  1. To get started, open the local copy inside your favourite text editor, and your browser.
  2. -
  3. Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!
  4. -
- -
-

Note: 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.

-
- -

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.

- -

Fixing syntax errors

- -

Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (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.

- -
    -
  1. Go to the tab that you've got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines:
  2. -
  3. 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: -
      -
    • A red "x" to indicate that this is an error.
    • -
    • An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function"
    • -
    • A "Learn More" link that links through to an MDN page that explains what this error means in huge amounts of detail.
    • -
    • 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.
    • -
    • 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.
    • -
    -
  4. -
  5. If we look at line 86 in our code editor, we'll find this line: -
    guessSubmit.addeventListener('click', checkGuess);
    -
  6. -
  7. 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 name-of-feature" on your favourite search engine. Here's a shortcut to save you some time in this instance: addEventListener().
  8. -
  9. 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 addeventListener to addEventListener should fix this. Do this now.
  10. -
- -
-

Note: See our TypeError: "x" is not a function reference page for more details about this error.

-
- -

Syntax errors round two

- -
    -
  1. Save your page and refresh, and you should see the error has gone.
  2. -
  3. Now if you try to enter a guess and press the Submit guess button, you'll see ... another error!
  4. -
  5. This time the error being reported is "TypeError: lowOrHi is null", on line 78. -
    Note: Null is a special value that means "nothing", or "no value". So lowOrHi has been declared and initialised, but not with any meaningful value — it has no type or value.
    - -
    Note: This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the checkGuess() { ... } 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 checkGuess() function was run by line 86.
    -
  6. -
  7. Have a look at line 78, and you'll see the following code: -
    lowOrHi.textContent = 'Last guess was too high!';
    -
  8. -
  9. This line is trying to set the textContent property of the lowOrHi variable to a text string, but it's not working because lowOrHi does not contain what it's supposed to. Let's see why this is — try searching for other instances of lowOrHi in the code. The earliest instance you'll find in the JavaScript is on line 48: -
    var lowOrHi = document.querySelector('lowOrHi');
    -
  10. -
  11. 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 null after this line has been run. Add the following code on line 49: -
    console.log(lowOrHi);
    - -
    -

    Note: console.log() is a really useful debugging function that prints a value to the console. So it will print the value of lowOrHi to the console as soon as we have tried to set it in line 48.

    -
    -
  12. -
  13. Save and refesh, and you should now see the console.log() result in your console. Sure enough, lowOrHi's value is null at this point, so there is definitely a problem with line 48.
  14. -
  15. Let's think about what the problem could be. Line 48 is using a document.querySelector() 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: -
    <p class="lowOrHi"></p>
    -
  16. -
  17. So we need a class selector here, which begins with a dot (.), but the selector being passed into the querySelector() method in line 48 has no dot. This could be the problem! Try changing lowOrHi to .lowOrHi in line 48.
  18. -
  19. Try saving and refreshing again, and your console.log() statement should return the <p> element we want. Phew! Another error fixed! You can delete your console.log() line now, or keep it to reference later on — your choice.
  20. -
- -
-

Note: See our TypeError: "x" is (not) "y" reference page for more details about this error.

-
- -

Syntax errors round three

- -
    -
  1. 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.
  2. -
  3. 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.
  4. -
  5. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change addeventListener to .addEventListener. Do this now.
  6. -
- -

A logic error

- -

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!

- -

There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.

- -
    -
  1. Search for the randomNumber 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: - -
    var randomNumber = Math.floor(Math.random()) + 1;
    - And the one that generates the random number before each subsequent game is around line 113:
  2. -
  3. -
    randomNumber = Math.floor(Math.random()) + 1;
    -
  4. -
  5. To check whether these lines are indeed the problem, let's turn to our friend console.log() again — insert the following line directly below each of the above two lines: -
    console.log(randomNumber);
    -
  6. -
  7. Save and refresh, then play a few games — you'll see that randomNumber is equal to 1 at each point where it is logged to the console.
  8. -
- -

Working through the logic

- -

To fix this, let's consider how this line is working. First, we invoke Math.random(), which generates a random decimal number between 0 and 1, e.g. 0.5675493843.

- -
Math.random()
- -

Next, we pass the result of invoking Math.random() through Math.floor(), which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:

- -
Math.floor(Math.random()) + 1
- -

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:

- -
Math.floor(Math.random()*100);
- -

Hence us wanting to add 1, to give us a random number between 1 and 100:

- -
Math.floor(Math.random()*100) + 1;
- -

Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!

- -

Other common errors

- -

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

- -

SyntaxError: missing ; before statement

- -

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 checkGuess() function:

- -
var userGuess = Number(guessField.value);
- -

to

- -
var userGuess === Number(guessField.value);
- -

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 (=) — which sets a variable to be equal to a value — with the strict equality operator (===), which tests whether one value is equal to another, and returns a true/false result.

- -
-

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

-
- -

The program always says you've won, regardless of the guess you enter

- -

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

- -
if (userGuess === randomNumber) {
- -

to

- -
if (userGuess = randomNumber) {
- -

the test would always return true, causing the program to report that the game has been won. Be careful!

- -

SyntaxError: missing ) after argument list

- -

This one is pretty simple — it generally means that you've missed the closing parenthesis off the end of a function/method call.

- -
-

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

-
- -

SyntaxError: missing : after property id

- -

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

- -
function checkGuess() {
- -

to

- -
function checkGuess( {
- -

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

- -

SyntaxError: missing } after function body

- -

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

- -

SyntaxError: expected expression, got 'string' or SyntaxError: unterminated string literal

- -

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

- -

For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go 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!

- -
-

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

-
- -

Summary

- -

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.

- -

See also

- -
- -
- -

{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}

- -

In this module

- - diff --git a/files/it/learn/javascript/first_steps/variabili/index.html b/files/it/learn/javascript/first_steps/variabili/index.html deleted file mode 100644 index 38da82e607..0000000000 --- a/files/it/learn/javascript/first_steps/variabili/index.html +++ /dev/null @@ -1,337 +0,0 @@ ---- -title: Memorizzazione delle informazioni necessarie - Variabili -slug: Learn/JavaScript/First_steps/Variabili -translation_of: Learn/JavaScript/First_steps/Variables ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}
- -

Dopo aver letto gli ultimi due articoli, ora dovresti sapere cos'è JavaScript, cosa può fare per te, come lo usi insieme ad altre tecnologie web e quali sono le sue caratteristiche principali da un livello elevato. In questo articolo, passeremo alle basi reali, esaminando come lavorare con i blocchi di base di JavaScript - Variabili.

- - - - - - - - - - - - -
Prerequisiti:Nozioni di base di informatica, comprensione di base di HTML e CSS, comprensione di cosa sia JavaScript
Obiettivo:Acquisire familiarità con le basi delle variabili JavaScript.
- -

Strumenti di cui hai bisogno

- -

In questo articolo ti verrà chiesto di digitare righe di codice per testare la tua comprensione del contenuto. Se si utilizza un browser desktop, il posto migliore per digitare il codice di esempio è la console JavaScript del browser (vedere Quali sono gli strumenti di sviluppo del browser per ulteriori informazioni su come accedere a questo strumento).

- -

Cosa è una variabile?

- -

Una variabile è un contenitore per un valore, come un numero che potremmo usare in una somma o una stringa che potremmo usare come parte di una frase. Ma una cosa speciale delle variabili è che i loro valori possono cambiare. Diamo un'occhiata a un semplice esempio:

- -
<button>Press me</button>
- -
const button = document.querySelector('button');
-
-button.onclick = function() {
-  let name = prompt('What is your name?');
-  alert('Hello ' + name + ', nice to see you!');
-}
- -

{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

- -

In questo esempio, premendo il bottone viene eseguito un paio di righe di codice. La prima riga apre una finestra sullo schermo che chiede al lettore di inserire il proprio nome, quindi memorizza il valore in una variabile. La seconda riga mostra un messaggio di benvenuto che include il loro nome, preso dal valore della variabile.

- -

Per capire perché questo è così utile, pensiamo a come scrivere questo esempio senza usare una variabile. Finirebbe per assomigliare a questo:

- -
let name = prompt('What is your name?');
-
-if (name === 'Adam') {
-  alert('Hello Adam, nice to see you!');
-} else if (name === 'Alan') {
-  alert('Hello Alan, nice to see you!');
-} else if (name === 'Bella') {
-  alert('Hello Bella, nice to see you!');
-} else if (name === 'Bianca') {
-  alert('Hello Bianca, nice to see you!');
-} else if (name === 'Chris') {
-  alert('Hello Chris, nice to see you!');
-}
-
-// ... and so on ...
- -

Potresti non comprendere appieno la sintassi che stiamo usando (ancora!), ma dovresti essere in grado di farti un'idea - se non avessimo variabili disponibili, dovremmo implementare un blocco di codice gigante che controlla quale sia il nome inserito e quindi visualizzare il messaggio appropriato per quel nome. Questo è ovviamente molto inefficiente (il codice è molto più grande, anche solo per cinque scelte), e semplicemente non funzionerebbe - non è possibile memorizzare tutte le possibili scelte.

- -

Le variabili hanno senso e, man mano che impari di più su JavaScript, inizieranno a diventare una seconda natura.

- -

Un'altra cosa speciale delle variabili è che possono contenere qualsiasi cosa, non solo stringhe e numeri. Le variabili possono anche contenere dati complessi e persino intere funzioni per fare cose sorprendenti. Imparerai di più su questo mentre procedi.

- -
-

Nota:Diciamo che le variabili contengono valori. Questa è una distinzione importante da fare. Le variabili non sono i valori stessi; sono contenitori per valori. Puoi pensare che siano come piccole scatole di cartone in cui puoi riporre le cose.

-
- -

- -

Dichiarare una variabile

- -

Per usare una variabile, devi prima crearla - più precisamente, dobbiamo dichiarare la variabile. Per fare ciò, utilizziamo la parola chiave var o let seguita dal nome che vuoi chiamare la tua variabile:

- -
let myName;
-let myAge;
- -

Qui stiamo creando due variabili chiamate myName e myAge. Prova a digitare queste righe nella console del tuo browser web. Successivamente, prova a creare una (o due) variabili chiamandole a tuo piacimento.

- -
-

Nota: In JavaScript, tutte le istruzioni del codice dovrebbero terminare con un punto e virgola (;) - il codice potrebbe funzionare correttamente per singole righe, ma probabilmente non funzionerà quando si scrivono più righe di codice insieme. Cerca di prendere l'abitudine di includerlo.

-
- -

Puoi verificare se questi valori ora esistono nell'ambiente di esecuzione digitando solo il nome della variabile, ad es.

- -
myName;
-myAge;
- -

Al momento non hanno valore; sono contenitori vuoti. Quando si immettono i nomi delle variabili, è necessario ottenere un valore undefined. Se non esistono, verrà visualizzato un messaggio di errore: "try typing in

- -
scoobyDoo;
- -
-

Nota: Non confondere una variabile esistente ma che non ha alcun valore definito con una variabile che non esiste affatto: sono cose molto diverse. Nell'analogia della scatola che hai visto sopra, non esistere significherebbe che non esiste una scatola (variabile) in cui inserire un valore. Nessun valore definito significherebbe che c'è una scatola, ma non ha alcun valore al suo interno.

-
- -

Inizializzare una Variabile

- -

Una volta che hai dichiarato una variabiale, puoi inizializzarla con un valore. Puoi farlo digitando il nome della variabile, seguito dal segno di uguale (=), seguito poi dal valore che vuoi dargli. Per esempio: 

- -
myName = 'Chris';
-myAge = 37;
- -

Prova a tornare alla console ora e digita queste linee. Dovresti vedere il valore che hai assegnato alla variabile restituita nella console per confermarla, in ogni caso. Ancora una volta, puoi restituire i valori delle variabili semplicemente digitandone il nome nella console. Riprova:

- -
myName;
-myAge;
- -

Puoi dichiarare e inizializzare una variabile nello stesso tempo, come questo: 

- -
let myDog = 'Rover';
- -

Questo è probabilmente ciò che farai la maggior parte del tempo, essendo il metodo più veloce rispetto alle due azioni separate. 

- -

Differenza tra var e let

- -

A questo punto potresti pensare "perchè abbiamo bisogno di due keywords (parole chiavi) per definire le variabili?? Perchè avere  var e let?".

- -

Le ragioni sono in qualche modo storiche.  Ai tempi della creazione di JavaScript, c'era solo var. Questa funziona fondamentalmente in molti casi, ma ha alcuni problemi nel modo in cui funziona — il suo design può qualche volta essere confuso o decisamente fastidioso. Così,  let è stata creata nella moderna versione di JavaScript, una nuova keyword (parola chiave) per creare variabili che funzionano differentemente da var, risolvendo i suoi problemi nel processo.

- -

Di seguito sono spiegate alcune semplici differenze. Non le affronteremo ora tutte, ma inizierai a scoprirle mentre impari più su JavaScript. (se vuoi davvero leggere su di loro ora, non esitare a controllare la nostra pagina di riferimento let).

- -

Per iniziare, se scrivi un multilinea JavaScript che dichiara e inizializza una variabile, puoi effettivamente dichiarare una variabile con var dopo averla inizializzata funzionerà comunque. Per esempio:

- -
myName = 'Chris';
-
-function logName() {
-  console.log(myName);
-}
-
-logName();
-
-var myName;
- -
-

Nota:  Questo non funziona quando digiti linee individuali in una JavaScript console, ma solo quando viene eseguita in linee multiple in un documento web. 

-
- -

Questo lfunziona a causa di hoisting — leggi var hoisting per maggiori dettagli sull'argomento. 

- -

Hoisting non funziona con  let. Se cambiamo var a let  nell'esempio precedente, da un errore. Questa è una buona cosa — dichiarare una variabile dopo che averla inizializzata si traduce in un codice confuso e difficile da capire.

- -

In secondo luogo, quando usi  var, puoi dichiarare la stessa variabile tutte le volte che vuoi, ma con  let non puoi. Quanto segue funzionerebbe: 

- -
var myName = 'Chris';
-var myName = 'Bob';
- -

Ma il seguente darebbe un errore sulla seconda linea: 

- -
let myName = 'Chris';
-let myName = 'Bob';
- -

Dovresti invece fare questo: 

- -
let myName = 'Chris';
-myName = 'Bob';
- -

Ancora una volta, questa è un scelta linquistica più corretta. Non c'è motivo di ridichiarare le variabili: rende le cose più confuse.

- -

Per queste ragioni e altre, noi raccomandiamo di usare let il più possibile nel tuo codice, piuttosto che var. Non ci sono motivi per usare var, a meno che non sia necessario supportare vecchie versioni di Internet Explorer proprio con il tuo codice.  ( let non è supportato fino fino alla versione 11, il moderno  Windows Edge browser supporta bene let).

- -
-

Nota:  Attualmente stiamo aggiornando il corso per usare più  let piuttosto che var. Abbi pazienza con noi!

-
- -

Aggiornare una variabile

- -

Una volta che una variabile è stata inizializzata con un valore, puoi cambiarlo (o aggiornarlo) dandogli semplicemente un valore differente. Prova a inserire le seguenti linee nella tua console: 

- -
myName = 'Bob';
-myAge = 40;
- -

Regole di denominazione delle variabili

- -

Puoi chiamare una variabile praticamente come preferisci, ma ci sono delle limitazioni. Generalmente, dovresti limitarti ad usare i caratteri latini (0-9, a-z, A-Z) e l'underscore ( _ ).

- - - -
-

Nota: Puoi trovare un elenco abbastanza completo di parole riservate da evitare a Lexical grammar — keywords.

-
- -

Esempi di nomi corretti: 

- -
age
-myAge
-init
-initialColor
-finalOutputValue
-audio1
-audio2
- -

Esempi di nomi errati: 

- -
1
-a
-_12
-myage
-MYAGE
-var
-Document
-skjfndskjfnbdskjfb
-thisisareallylongstupidvariablenameman
- -

Esempi di nomi soggetti a errori: 

- -
var
-Document
-
- -

Prova a creare qualche altra variabile ora, tenendo presente le indicazioni sopra riportate. 

- -

Tipi di Variabili

- -

Esistono diversi tipi di dati che possiamo archiviare in variabili. In questa sezione li descriveremo in breve, quindi in articoli futuri, imparerai su di loro in modo più dettagliato.

- -

Finora abbiamo esaminato i primi due, ma che ne sono altri. 

- -

Numeri

- -

Puoi memorizzare numeri nelle variabili, numeri interi come 30  o numeri decimali come 2,456 (chiamati anche numeri mobili o in virgola mobile). Non è necessario dichiarare i tipi di variabili in JavaScript, a differenza di altri linguaggi di programmazione. Quando dai a una variabile un valore numerico, non si usa le virgolette:

- -
let myAge = 17;
- -

Stringhe

- -

Le stringhe sono pezzi di testo. Quando dai a una variabile un valore di una stringa, hai bisogno di metterla in singole o doppie virgolette; altrimenti, JavaScript cerca di interpretarlo come un altro nome della variabile. 

- -
let dolphinGoodbye = 'So long and thanks for all the fish';
- -

Booleani

- -

I booleani sono dei valori vero/falso — possono avere due valori truefalse. Questi sono generalmente usati per testare delle condizioni, dopo di che il codice viene eseguito come appropriato . Ad esempio, un semplice caso sarebbe:

- -
let iAmAlive = true;
- -

Considerando che in realtà sarebbe usato più così:

- -
let test = 6 < 3;
- -

Questo sta usando l'operatore "minore di" (<) per verificare se 6 è minore di 3. Come ci si potrebbe aspettare, restituisce false, perché 6 non è inferiore a 3! Imparerai molto di più su questi operatori più avanti nel corso.

- -

Arrays

- -

Un  array è un singolo oggetto che contiene valori multipli racchiusi in parentesi quadre e separate da virgole. Prova a inserire le seguenti linee nella tua console:

- -
let myNameArray = ['Chris', 'Bob', 'Jim'];
-let myNumberArray = [10, 15, 40];
- -

Una volta che gli  arrays sono definiti,  è possibile accedere a ciascun valore in base alla posizione all'interno dell'array. Prova queste linee:

- -
myNameArray[0]; // should return 'Chris'
-myNumberArray[2]; // should return 40
- -

Le parentesi quadre specificano un valore di indice corrispondente alla posizione del valore che si desidera restituire. Potresti aver notato che gli array in JavaScript sono indicizzatI a zero: il primo elemento si trova all'indice 0.

- -

Puoi imparare molto sugli arrays in un futuro articolo.

- -

Oggetti

- -

In programmazione, un oggetto è una struttura di codice che modella un oggetto reale. Puoi avere un oggetto semplice che rappresenta una box e contiene informazioni sulla sua larghezza, lunghezza e altezza, oppure potresti avere un oggetto che rappresenta una persona e contenere dati sul suo nome, altezza, peso, quale lingua parla, come salutarli
- e altro ancora.

- -

Prova a inserire il seguente codice nella tua console:

- -
let dog = { name : 'Spot', breed : 'Dalmatian' };
- -

Per recuperare le informazioni archiviate nell'oggetto, è possibile utilizzare la seguente sintassi:

- -
dog.name
- -

Per ora non esamineremo più gli oggetti: puoi saperne di più su quelli in un  modulo futuro.

- -

Tipizzazione dinamica

- -

JavaScript è un "linguaggio a tipizzazione dinamica", questo significa che,  a differenza di altri linguaggi, non è necessario specificare quale tipo di dati conterrà una variabile (numeri, stringhe, array, ecc.).

- -

Ad esempio, se dichiari una variabile e le assegni un valore racchiuso tra virgolette, il browser considera la variabile come una stringa:

- -
let myString = 'Hello';
- -

Anche se il valore contiene numeri, è comunque una stringa, quindi fai attenzione:

- -
let myNumber = '500'; // oops, questa è ancora una stringa
-typeof myNumber;
-myNumber = 500; // molto meglio - adesso questo è un numero
-typeof myNumber;
- -

Prova a inserire le quattro righe sopra nella console una per una e guarda quali sono i risultati. Noterai che stiamo usando un speciale operatore chiamato typeof- questo restituisce il tipo di dati della variabile che scrivi dopo. La prima volta che viene chiamato, dovrebbe restituire string, poiché a quel punto la variabile myNumber contiene una stringa, '500'.
- Dai un'occhiata e vedi cosa restituisce la seconda volta che lo chiami.

- -

Costanti in JavaScript

- -

Molti linguaggi di programmazione hanno il concetto di costante - un valore che una volta dichiarato non può mai essere modificato. Ci sono molte ragioni per cui vorresti farlo, dalla sicurezza (se uno script di terze parti ha cambiato tali valori potrebbe causare problemi) al debug e alla comprensione del codice (è più difficile cambiare accidentalmente valori che non dovrebbero essere cambiati e fare confusione).

- -

All'inizio di JavaScript, le costanti non esistevano. Nel moderno JavaScript, abbiamo la parola chiave const, che ci consente di memorizzare valori che non possono mai essere modificati:

- -
const daysInWeek = 7;
-const hoursInDay = 24;
- -

const lavora esattamente come let, eccetto che non puoi dare aconst un nuovo valore. Nell'esempio seguente, la seconda linea genera un errore:

- -
const daysInWeek = 7;
-daysInWeek = 8;
- -

Sommario 

- -

Ormai dovresti conoscere una quantità ragionevole di variabili JavaScript e come crearle. Nel prossimo articolo, ci concentreremo sui numeri in modo più dettagliato, esaminando come eseguire la matematica di base in JavaScript.

- -

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}

- -

In this module

- - diff --git a/files/it/learn/javascript/first_steps/variables/index.html b/files/it/learn/javascript/first_steps/variables/index.html new file mode 100644 index 0000000000..38da82e607 --- /dev/null +++ b/files/it/learn/javascript/first_steps/variables/index.html @@ -0,0 +1,337 @@ +--- +title: Memorizzazione delle informazioni necessarie - Variabili +slug: Learn/JavaScript/First_steps/Variabili +translation_of: Learn/JavaScript/First_steps/Variables +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}
+ +

Dopo aver letto gli ultimi due articoli, ora dovresti sapere cos'è JavaScript, cosa può fare per te, come lo usi insieme ad altre tecnologie web e quali sono le sue caratteristiche principali da un livello elevato. In questo articolo, passeremo alle basi reali, esaminando come lavorare con i blocchi di base di JavaScript - Variabili.

+ + + + + + + + + + + + +
Prerequisiti:Nozioni di base di informatica, comprensione di base di HTML e CSS, comprensione di cosa sia JavaScript
Obiettivo:Acquisire familiarità con le basi delle variabili JavaScript.
+ +

Strumenti di cui hai bisogno

+ +

In questo articolo ti verrà chiesto di digitare righe di codice per testare la tua comprensione del contenuto. Se si utilizza un browser desktop, il posto migliore per digitare il codice di esempio è la console JavaScript del browser (vedere Quali sono gli strumenti di sviluppo del browser per ulteriori informazioni su come accedere a questo strumento).

+ +

Cosa è una variabile?

+ +

Una variabile è un contenitore per un valore, come un numero che potremmo usare in una somma o una stringa che potremmo usare come parte di una frase. Ma una cosa speciale delle variabili è che i loro valori possono cambiare. Diamo un'occhiata a un semplice esempio:

+ +
<button>Press me</button>
+ +
const button = document.querySelector('button');
+
+button.onclick = function() {
+  let name = prompt('What is your name?');
+  alert('Hello ' + name + ', nice to see you!');
+}
+ +

{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

+ +

In questo esempio, premendo il bottone viene eseguito un paio di righe di codice. La prima riga apre una finestra sullo schermo che chiede al lettore di inserire il proprio nome, quindi memorizza il valore in una variabile. La seconda riga mostra un messaggio di benvenuto che include il loro nome, preso dal valore della variabile.

+ +

Per capire perché questo è così utile, pensiamo a come scrivere questo esempio senza usare una variabile. Finirebbe per assomigliare a questo:

+ +
let name = prompt('What is your name?');
+
+if (name === 'Adam') {
+  alert('Hello Adam, nice to see you!');
+} else if (name === 'Alan') {
+  alert('Hello Alan, nice to see you!');
+} else if (name === 'Bella') {
+  alert('Hello Bella, nice to see you!');
+} else if (name === 'Bianca') {
+  alert('Hello Bianca, nice to see you!');
+} else if (name === 'Chris') {
+  alert('Hello Chris, nice to see you!');
+}
+
+// ... and so on ...
+ +

Potresti non comprendere appieno la sintassi che stiamo usando (ancora!), ma dovresti essere in grado di farti un'idea - se non avessimo variabili disponibili, dovremmo implementare un blocco di codice gigante che controlla quale sia il nome inserito e quindi visualizzare il messaggio appropriato per quel nome. Questo è ovviamente molto inefficiente (il codice è molto più grande, anche solo per cinque scelte), e semplicemente non funzionerebbe - non è possibile memorizzare tutte le possibili scelte.

+ +

Le variabili hanno senso e, man mano che impari di più su JavaScript, inizieranno a diventare una seconda natura.

+ +

Un'altra cosa speciale delle variabili è che possono contenere qualsiasi cosa, non solo stringhe e numeri. Le variabili possono anche contenere dati complessi e persino intere funzioni per fare cose sorprendenti. Imparerai di più su questo mentre procedi.

+ +
+

Nota:Diciamo che le variabili contengono valori. Questa è una distinzione importante da fare. Le variabili non sono i valori stessi; sono contenitori per valori. Puoi pensare che siano come piccole scatole di cartone in cui puoi riporre le cose.

+
+ +

+ +

Dichiarare una variabile

+ +

Per usare una variabile, devi prima crearla - più precisamente, dobbiamo dichiarare la variabile. Per fare ciò, utilizziamo la parola chiave var o let seguita dal nome che vuoi chiamare la tua variabile:

+ +
let myName;
+let myAge;
+ +

Qui stiamo creando due variabili chiamate myName e myAge. Prova a digitare queste righe nella console del tuo browser web. Successivamente, prova a creare una (o due) variabili chiamandole a tuo piacimento.

+ +
+

Nota: In JavaScript, tutte le istruzioni del codice dovrebbero terminare con un punto e virgola (;) - il codice potrebbe funzionare correttamente per singole righe, ma probabilmente non funzionerà quando si scrivono più righe di codice insieme. Cerca di prendere l'abitudine di includerlo.

+
+ +

Puoi verificare se questi valori ora esistono nell'ambiente di esecuzione digitando solo il nome della variabile, ad es.

+ +
myName;
+myAge;
+ +

Al momento non hanno valore; sono contenitori vuoti. Quando si immettono i nomi delle variabili, è necessario ottenere un valore undefined. Se non esistono, verrà visualizzato un messaggio di errore: "try typing in

+ +
scoobyDoo;
+ +
+

Nota: Non confondere una variabile esistente ma che non ha alcun valore definito con una variabile che non esiste affatto: sono cose molto diverse. Nell'analogia della scatola che hai visto sopra, non esistere significherebbe che non esiste una scatola (variabile) in cui inserire un valore. Nessun valore definito significherebbe che c'è una scatola, ma non ha alcun valore al suo interno.

+
+ +

Inizializzare una Variabile

+ +

Una volta che hai dichiarato una variabiale, puoi inizializzarla con un valore. Puoi farlo digitando il nome della variabile, seguito dal segno di uguale (=), seguito poi dal valore che vuoi dargli. Per esempio: 

+ +
myName = 'Chris';
+myAge = 37;
+ +

Prova a tornare alla console ora e digita queste linee. Dovresti vedere il valore che hai assegnato alla variabile restituita nella console per confermarla, in ogni caso. Ancora una volta, puoi restituire i valori delle variabili semplicemente digitandone il nome nella console. Riprova:

+ +
myName;
+myAge;
+ +

Puoi dichiarare e inizializzare una variabile nello stesso tempo, come questo: 

+ +
let myDog = 'Rover';
+ +

Questo è probabilmente ciò che farai la maggior parte del tempo, essendo il metodo più veloce rispetto alle due azioni separate. 

+ +

Differenza tra var e let

+ +

A questo punto potresti pensare "perchè abbiamo bisogno di due keywords (parole chiavi) per definire le variabili?? Perchè avere  var e let?".

+ +

Le ragioni sono in qualche modo storiche.  Ai tempi della creazione di JavaScript, c'era solo var. Questa funziona fondamentalmente in molti casi, ma ha alcuni problemi nel modo in cui funziona — il suo design può qualche volta essere confuso o decisamente fastidioso. Così,  let è stata creata nella moderna versione di JavaScript, una nuova keyword (parola chiave) per creare variabili che funzionano differentemente da var, risolvendo i suoi problemi nel processo.

+ +

Di seguito sono spiegate alcune semplici differenze. Non le affronteremo ora tutte, ma inizierai a scoprirle mentre impari più su JavaScript. (se vuoi davvero leggere su di loro ora, non esitare a controllare la nostra pagina di riferimento let).

+ +

Per iniziare, se scrivi un multilinea JavaScript che dichiara e inizializza una variabile, puoi effettivamente dichiarare una variabile con var dopo averla inizializzata funzionerà comunque. Per esempio:

+ +
myName = 'Chris';
+
+function logName() {
+  console.log(myName);
+}
+
+logName();
+
+var myName;
+ +
+

Nota:  Questo non funziona quando digiti linee individuali in una JavaScript console, ma solo quando viene eseguita in linee multiple in un documento web. 

+
+ +

Questo lfunziona a causa di hoisting — leggi var hoisting per maggiori dettagli sull'argomento. 

+ +

Hoisting non funziona con  let. Se cambiamo var a let  nell'esempio precedente, da un errore. Questa è una buona cosa — dichiarare una variabile dopo che averla inizializzata si traduce in un codice confuso e difficile da capire.

+ +

In secondo luogo, quando usi  var, puoi dichiarare la stessa variabile tutte le volte che vuoi, ma con  let non puoi. Quanto segue funzionerebbe: 

+ +
var myName = 'Chris';
+var myName = 'Bob';
+ +

Ma il seguente darebbe un errore sulla seconda linea: 

+ +
let myName = 'Chris';
+let myName = 'Bob';
+ +

Dovresti invece fare questo: 

+ +
let myName = 'Chris';
+myName = 'Bob';
+ +

Ancora una volta, questa è un scelta linquistica più corretta. Non c'è motivo di ridichiarare le variabili: rende le cose più confuse.

+ +

Per queste ragioni e altre, noi raccomandiamo di usare let il più possibile nel tuo codice, piuttosto che var. Non ci sono motivi per usare var, a meno che non sia necessario supportare vecchie versioni di Internet Explorer proprio con il tuo codice.  ( let non è supportato fino fino alla versione 11, il moderno  Windows Edge browser supporta bene let).

+ +
+

Nota:  Attualmente stiamo aggiornando il corso per usare più  let piuttosto che var. Abbi pazienza con noi!

+
+ +

Aggiornare una variabile

+ +

Una volta che una variabile è stata inizializzata con un valore, puoi cambiarlo (o aggiornarlo) dandogli semplicemente un valore differente. Prova a inserire le seguenti linee nella tua console: 

+ +
myName = 'Bob';
+myAge = 40;
+ +

Regole di denominazione delle variabili

+ +

Puoi chiamare una variabile praticamente come preferisci, ma ci sono delle limitazioni. Generalmente, dovresti limitarti ad usare i caratteri latini (0-9, a-z, A-Z) e l'underscore ( _ ).

+ + + +
+

Nota: Puoi trovare un elenco abbastanza completo di parole riservate da evitare a Lexical grammar — keywords.

+
+ +

Esempi di nomi corretti: 

+ +
age
+myAge
+init
+initialColor
+finalOutputValue
+audio1
+audio2
+ +

Esempi di nomi errati: 

+ +
1
+a
+_12
+myage
+MYAGE
+var
+Document
+skjfndskjfnbdskjfb
+thisisareallylongstupidvariablenameman
+ +

Esempi di nomi soggetti a errori: 

+ +
var
+Document
+
+ +

Prova a creare qualche altra variabile ora, tenendo presente le indicazioni sopra riportate. 

+ +

Tipi di Variabili

+ +

Esistono diversi tipi di dati che possiamo archiviare in variabili. In questa sezione li descriveremo in breve, quindi in articoli futuri, imparerai su di loro in modo più dettagliato.

+ +

Finora abbiamo esaminato i primi due, ma che ne sono altri. 

+ +

Numeri

+ +

Puoi memorizzare numeri nelle variabili, numeri interi come 30  o numeri decimali come 2,456 (chiamati anche numeri mobili o in virgola mobile). Non è necessario dichiarare i tipi di variabili in JavaScript, a differenza di altri linguaggi di programmazione. Quando dai a una variabile un valore numerico, non si usa le virgolette:

+ +
let myAge = 17;
+ +

Stringhe

+ +

Le stringhe sono pezzi di testo. Quando dai a una variabile un valore di una stringa, hai bisogno di metterla in singole o doppie virgolette; altrimenti, JavaScript cerca di interpretarlo come un altro nome della variabile. 

+ +
let dolphinGoodbye = 'So long and thanks for all the fish';
+ +

Booleani

+ +

I booleani sono dei valori vero/falso — possono avere due valori truefalse. Questi sono generalmente usati per testare delle condizioni, dopo di che il codice viene eseguito come appropriato . Ad esempio, un semplice caso sarebbe:

+ +
let iAmAlive = true;
+ +

Considerando che in realtà sarebbe usato più così:

+ +
let test = 6 < 3;
+ +

Questo sta usando l'operatore "minore di" (<) per verificare se 6 è minore di 3. Come ci si potrebbe aspettare, restituisce false, perché 6 non è inferiore a 3! Imparerai molto di più su questi operatori più avanti nel corso.

+ +

Arrays

+ +

Un  array è un singolo oggetto che contiene valori multipli racchiusi in parentesi quadre e separate da virgole. Prova a inserire le seguenti linee nella tua console:

+ +
let myNameArray = ['Chris', 'Bob', 'Jim'];
+let myNumberArray = [10, 15, 40];
+ +

Una volta che gli  arrays sono definiti,  è possibile accedere a ciascun valore in base alla posizione all'interno dell'array. Prova queste linee:

+ +
myNameArray[0]; // should return 'Chris'
+myNumberArray[2]; // should return 40
+ +

Le parentesi quadre specificano un valore di indice corrispondente alla posizione del valore che si desidera restituire. Potresti aver notato che gli array in JavaScript sono indicizzatI a zero: il primo elemento si trova all'indice 0.

+ +

Puoi imparare molto sugli arrays in un futuro articolo.

+ +

Oggetti

+ +

In programmazione, un oggetto è una struttura di codice che modella un oggetto reale. Puoi avere un oggetto semplice che rappresenta una box e contiene informazioni sulla sua larghezza, lunghezza e altezza, oppure potresti avere un oggetto che rappresenta una persona e contenere dati sul suo nome, altezza, peso, quale lingua parla, come salutarli
+ e altro ancora.

+ +

Prova a inserire il seguente codice nella tua console:

+ +
let dog = { name : 'Spot', breed : 'Dalmatian' };
+ +

Per recuperare le informazioni archiviate nell'oggetto, è possibile utilizzare la seguente sintassi:

+ +
dog.name
+ +

Per ora non esamineremo più gli oggetti: puoi saperne di più su quelli in un  modulo futuro.

+ +

Tipizzazione dinamica

+ +

JavaScript è un "linguaggio a tipizzazione dinamica", questo significa che,  a differenza di altri linguaggi, non è necessario specificare quale tipo di dati conterrà una variabile (numeri, stringhe, array, ecc.).

+ +

Ad esempio, se dichiari una variabile e le assegni un valore racchiuso tra virgolette, il browser considera la variabile come una stringa:

+ +
let myString = 'Hello';
+ +

Anche se il valore contiene numeri, è comunque una stringa, quindi fai attenzione:

+ +
let myNumber = '500'; // oops, questa è ancora una stringa
+typeof myNumber;
+myNumber = 500; // molto meglio - adesso questo è un numero
+typeof myNumber;
+ +

Prova a inserire le quattro righe sopra nella console una per una e guarda quali sono i risultati. Noterai che stiamo usando un speciale operatore chiamato typeof- questo restituisce il tipo di dati della variabile che scrivi dopo. La prima volta che viene chiamato, dovrebbe restituire string, poiché a quel punto la variabile myNumber contiene una stringa, '500'.
+ Dai un'occhiata e vedi cosa restituisce la seconda volta che lo chiami.

+ +

Costanti in JavaScript

+ +

Molti linguaggi di programmazione hanno il concetto di costante - un valore che una volta dichiarato non può mai essere modificato. Ci sono molte ragioni per cui vorresti farlo, dalla sicurezza (se uno script di terze parti ha cambiato tali valori potrebbe causare problemi) al debug e alla comprensione del codice (è più difficile cambiare accidentalmente valori che non dovrebbero essere cambiati e fare confusione).

+ +

All'inizio di JavaScript, le costanti non esistevano. Nel moderno JavaScript, abbiamo la parola chiave const, che ci consente di memorizzare valori che non possono mai essere modificati:

+ +
const daysInWeek = 7;
+const hoursInDay = 24;
+ +

const lavora esattamente come let, eccetto che non puoi dare aconst un nuovo valore. Nell'esempio seguente, la seconda linea genera un errore:

+ +
const daysInWeek = 7;
+daysInWeek = 8;
+ +

Sommario 

+ +

Ormai dovresti conoscere una quantità ragionevole di variabili JavaScript e come crearle. Nel prossimo articolo, ci concentreremo sui numeri in modo più dettagliato, esaminando come eseguire la matematica di base in JavaScript.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/it/learn/javascript/first_steps/what_went_wrong/index.html b/files/it/learn/javascript/first_steps/what_went_wrong/index.html new file mode 100644 index 0000000000..1fa4343de8 --- /dev/null +++ b/files/it/learn/javascript/first_steps/what_went_wrong/index.html @@ -0,0 +1,253 @@ +--- +title: Cosa è andato storto? Problemi con Javacript +slug: Learn/JavaScript/First_steps/Cosa_è_andato_storto +translation_of: Learn/JavaScript/First_steps/What_went_wrong +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}
+ +

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 .

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective:To gain the ability and confidence to start fixing simple problems in your own code.
+ +

Types of error

+ +

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

+ + + +

Okay, so it's not quite that 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.

+ +

An erroneous example

+ +

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 number-game-errors.html (see it running live here).

+ +
    +
  1. To get started, open the local copy inside your favourite text editor, and your browser.
  2. +
  3. Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!
  4. +
+ +
+

Note: 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.

+
+ +

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.

+ +

Fixing syntax errors

+ +

Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (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.

+ +
    +
  1. Go to the tab that you've got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines:
  2. +
  3. 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: +
      +
    • A red "x" to indicate that this is an error.
    • +
    • An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function"
    • +
    • A "Learn More" link that links through to an MDN page that explains what this error means in huge amounts of detail.
    • +
    • 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.
    • +
    • 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.
    • +
    +
  4. +
  5. If we look at line 86 in our code editor, we'll find this line: +
    guessSubmit.addeventListener('click', checkGuess);
    +
  6. +
  7. 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 name-of-feature" on your favourite search engine. Here's a shortcut to save you some time in this instance: addEventListener().
  8. +
  9. 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 addeventListener to addEventListener should fix this. Do this now.
  10. +
+ +
+

Note: See our TypeError: "x" is not a function reference page for more details about this error.

+
+ +

Syntax errors round two

+ +
    +
  1. Save your page and refresh, and you should see the error has gone.
  2. +
  3. Now if you try to enter a guess and press the Submit guess button, you'll see ... another error!
  4. +
  5. This time the error being reported is "TypeError: lowOrHi is null", on line 78. +
    Note: Null is a special value that means "nothing", or "no value". So lowOrHi has been declared and initialised, but not with any meaningful value — it has no type or value.
    + +
    Note: This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the checkGuess() { ... } 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 checkGuess() function was run by line 86.
    +
  6. +
  7. Have a look at line 78, and you'll see the following code: +
    lowOrHi.textContent = 'Last guess was too high!';
    +
  8. +
  9. This line is trying to set the textContent property of the lowOrHi variable to a text string, but it's not working because lowOrHi does not contain what it's supposed to. Let's see why this is — try searching for other instances of lowOrHi in the code. The earliest instance you'll find in the JavaScript is on line 48: +
    var lowOrHi = document.querySelector('lowOrHi');
    +
  10. +
  11. 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 null after this line has been run. Add the following code on line 49: +
    console.log(lowOrHi);
    + +
    +

    Note: console.log() is a really useful debugging function that prints a value to the console. So it will print the value of lowOrHi to the console as soon as we have tried to set it in line 48.

    +
    +
  12. +
  13. Save and refesh, and you should now see the console.log() result in your console. Sure enough, lowOrHi's value is null at this point, so there is definitely a problem with line 48.
  14. +
  15. Let's think about what the problem could be. Line 48 is using a document.querySelector() 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: +
    <p class="lowOrHi"></p>
    +
  16. +
  17. So we need a class selector here, which begins with a dot (.), but the selector being passed into the querySelector() method in line 48 has no dot. This could be the problem! Try changing lowOrHi to .lowOrHi in line 48.
  18. +
  19. Try saving and refreshing again, and your console.log() statement should return the <p> element we want. Phew! Another error fixed! You can delete your console.log() line now, or keep it to reference later on — your choice.
  20. +
+ +
+

Note: See our TypeError: "x" is (not) "y" reference page for more details about this error.

+
+ +

Syntax errors round three

+ +
    +
  1. 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.
  2. +
  3. 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.
  4. +
  5. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change addeventListener to .addEventListener. Do this now.
  6. +
+ +

A logic error

+ +

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!

+ +

There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.

+ +
    +
  1. Search for the randomNumber 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: + +
    var randomNumber = Math.floor(Math.random()) + 1;
    + And the one that generates the random number before each subsequent game is around line 113:
  2. +
  3. +
    randomNumber = Math.floor(Math.random()) + 1;
    +
  4. +
  5. To check whether these lines are indeed the problem, let's turn to our friend console.log() again — insert the following line directly below each of the above two lines: +
    console.log(randomNumber);
    +
  6. +
  7. Save and refresh, then play a few games — you'll see that randomNumber is equal to 1 at each point where it is logged to the console.
  8. +
+ +

Working through the logic

+ +

To fix this, let's consider how this line is working. First, we invoke Math.random(), which generates a random decimal number between 0 and 1, e.g. 0.5675493843.

+ +
Math.random()
+ +

Next, we pass the result of invoking Math.random() through Math.floor(), which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:

+ +
Math.floor(Math.random()) + 1
+ +

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:

+ +
Math.floor(Math.random()*100);
+ +

Hence us wanting to add 1, to give us a random number between 1 and 100:

+ +
Math.floor(Math.random()*100) + 1;
+ +

Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!

+ +

Other common errors

+ +

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

+ +

SyntaxError: missing ; before statement

+ +

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 checkGuess() function:

+ +
var userGuess = Number(guessField.value);
+ +

to

+ +
var userGuess === Number(guessField.value);
+ +

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 (=) — which sets a variable to be equal to a value — with the strict equality operator (===), which tests whether one value is equal to another, and returns a true/false result.

+ +
+

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

+
+ +

The program always says you've won, regardless of the guess you enter

+ +

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

+ +
if (userGuess === randomNumber) {
+ +

to

+ +
if (userGuess = randomNumber) {
+ +

the test would always return true, causing the program to report that the game has been won. Be careful!

+ +

SyntaxError: missing ) after argument list

+ +

This one is pretty simple — it generally means that you've missed the closing parenthesis off the end of a function/method call.

+ +
+

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

+
+ +

SyntaxError: missing : after property id

+ +

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

+ +
function checkGuess() {
+ +

to

+ +
function checkGuess( {
+ +

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

+ +

SyntaxError: missing } after function body

+ +

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

+ +

SyntaxError: expected expression, got 'string' or SyntaxError: unterminated string literal

+ +

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

+ +

For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go 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!

+ +
+

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

+
+ +

Summary

+ +

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.

+ +

See also

+ +
+ +
+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + -- cgit v1.2.3-54-g00ecf