diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/it/learn/javascript/first_steps | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/it/learn/javascript/first_steps')
3 files changed, 658 insertions, 0 deletions
diff --git a/files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html b/files/it/learn/javascript/first_steps/cosa_è_andato_storto/index.html new file mode 100644 index 0000000000..1fa4343de8 --- /dev/null +++ b/files/it/learn/javascript/first_steps/cosa_è_andato_storto/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 +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">Quando abbiamo realizzato il gioco "Indovina il numero" nell'articole precedente, potresti esserti accorto che non funziona. Niente paura — questo articolo mira ad aiutarti e non farti strappare i capelli per tali problemi, fornendoti alcuni semplici aiuti su come trovare e correggere gli errori in JavaScript .</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To gain the ability and confidence to start fixing simple problems in your own code.</td> + </tr> + </tbody> +</table> + +<h2 id="Types_of_error">Types of error</h2> + +<p>Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:</p> + +<ul> + <li><strong>Syntax errors</strong>: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!</li> + <li><strong>Logic errors</strong>: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't a resulting error message to direct you to the source of the error.</li> +</ul> + +<p>Okay, so it's not quite <em>that</em> simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.</p> + +<h2 id="An_erroneous_example">An erroneous example</h2> + +<p>To get started, let's return to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced. Go to Github and make yourself a local copy of <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">number-game-errors.html</a> (see it <a href="http://mdn.github.io/learning-area/javascript/introduction-to-js-1/troubleshooting/number-game-errors.html">running live here</a>).</p> + +<ol> + <li>To get started, open the local copy inside your favourite text editor, and your browser.</li> + <li>Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.</p> +</div> + +<p>At this point, let's consult the developer console to see if we can see any syntax errors, then try to fix them. You'll learn how below.</p> + +<h2 id="Fixing_syntax_errors">Fixing syntax errors</h2> + +<p>Earlier on in the course we got you to type some simple JavaScript commands into the <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">developer tools JavaScript console</a> (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting.</p> + +<ol> + <li>Go to the tab that you've got <code>number-game-errors.html</code> open in, and open your JavaScript console. You should see an error message along the following lines: <img alt="" src="https://mdn.mozillademos.org/files/13496/not-a-function.png" style="display: block; margin: 0 auto;"></li> + <li>This is a pretty easy error to track down, and the browser gives you several useful bits of information to help you out (the screenshot above is from Firefox, but other browsers provide similar information). From left to right, we've got: + <ul> + <li>A red "x" to indicate that this is an error.</li> + <li>An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function"</li> + <li>A "Learn More" link that links through to an MDN page that explains what this error means in huge amounts of detail.</li> + <li>The name of the JavaScript file, which links through to the Debugger tab of the devtools. If you follow this link, you'll see the exact line where the error is highlighted.</li> + <li>The line number where the error is, and the character number in that line where the error is first seen. In this case, we've got line 86, character number 3.</li> + </ul> + </li> + <li>If we look at line 86 in our code editor, we'll find this line: + <pre class="brush: js">guessSubmit.addeventListener('click', checkGuess);</pre> + </li> + <li>The error message says "guessSubmit.addeventListener is not a function", so we've probably spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn <em>name-of-feature</em>" on your favourite search engine. Here's a shortcut to save you some time in this instance: <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener()</a></code>.</li> + <li>So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case sensitive, so any slight difference in spelling or casing will cause an error. Changing <code>addeventListener</code> to <code>addEventListener</code> should fix this. Do this now.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function">TypeError: "x" is not a function</a> reference page for more details about this error.</p> +</div> + +<h3 id="Syntax_errors_round_two">Syntax errors round two</h3> + +<ol> + <li>Save your page and refresh, and you should see the error has gone.</li> + <li>Now if you try to enter a guess and press the Submit guess button, you'll see ... another error! <img alt="" src="https://mdn.mozillademos.org/files/13498/variable-is-null.png" style="display: block; margin: 0 auto;"></li> + <li>This time the error being reported is "TypeError: lowOrHi is null", on line 78. + <div class="note"><strong>Note</strong>: <code><a href="/en-US/docs/Glossary/Null">Null</a></code> is a special value that means "nothing", or "no value". So <code>lowOrHi</code> has been declared and initialised, but not with any meaningful value — it has no type or value.</div> + + <div class="note"><strong>Note</strong>: This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the <code>checkGuess() { ... }</code> block). As you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the <code>checkGuess()</code> function was run by line 86.</div> + </li> + <li>Have a look at line 78, and you'll see the following code: + <pre class="brush: js">lowOrHi.textContent = 'Last guess was too high!';</pre> + </li> + <li>This line is trying to set the <code>textContent</code> property of the <code>lowOrHi</code> variable to a text string, but it's not working because <code>lowOrHi</code> does not contain what it's supposed to. Let's see why this is — try searching for other instances of <code>lowOrHi</code> in the code. The earliest instance you'll find in the JavaScript is on line 48: + <pre class="brush: js">var lowOrHi = document.querySelector('lowOrHi');</pre> + </li> + <li>At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's check whether the value is <code>null</code> after this line has been run. Add the following code on line 49: + <pre class="brush: js">console.log(lowOrHi);</pre> + + <div class="note"> + <p><strong>Note</strong>: <code><a href="/en-US/docs/Web/API/Console/log">console.log()</a></code> is a really useful debugging function that prints a value to the console. So it will print the value of <code>lowOrHi</code> to the console as soon as we have tried to set it in line 48.</p> + </div> + </li> + <li>Save and refesh, and you should now see the <code>console.log()</code> result in your console. <img alt="" src="https://mdn.mozillademos.org/files/13494/console-log-output.png" style="display: block; margin: 0 auto;"> Sure enough, <code>lowOrHi</code>'s value is <code>null</code> at this point, so there is definitely a problem with line 48.</li> + <li>Let's think about what the problem could be. Line 48 is using a <code><a href="/en-US/docs/Web/API/Document/querySelector">document.querySelector()</a></code> method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question: + <pre class="brush: js"><p class="lowOrHi"></p></pre> + </li> + <li>So we need a class selector here, which begins with a dot (.), but the selector being passed into the <code>querySelector()</code> method in line 48 has no dot. This could be the problem! Try changing <code>lowOrHi</code> to <code>.lowOrHi</code> in line 48.</li> + <li>Try saving and refreshing again, and your <code>console.log()</code> statement should return the <code><p></code> element we want. Phew! Another error fixed! You can delete your <code>console.log()</code> line now, or keep it to reference later on — your choice.</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_type">TypeError: "x" is (not) "y"</a> reference page for more details about this error.</p> +</div> + +<h3 id="Syntax_errors_round_three">Syntax errors round three</h3> + +<ol> + <li>Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of lives.</li> + <li>At that point, the game fails again, and the same error is spat out that we got at the beginning — "TypeError: resetButton.addeventListener is not a function"! However, this time it's listed as coming from line 94.</li> + <li>Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change <code>addeventListener</code> to <code>.addEventListener</code>. Do this now.</li> +</ol> + +<h2 id="A_logic_error">A logic error</h2> + +<p>At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the "random" number you've got to guess is always 1. Definitely not quite how we want the game to play out!</p> + +<p>There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.</p> + +<ol> + <li>Search for the <code>randomNumber</code> variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 44: + + <pre class="brush: js">var randomNumber = Math.floor(Math.random()) + 1;</pre> + And the one that generates the random number before each subsequent game is around line 113:</li> + <li> + <pre class="brush: js">randomNumber = Math.floor(Math.random()) + 1;</pre> + </li> + <li>To check whether these lines are indeed the problem, let's turn to our friend <code>console.log()</code> again — insert the following line directly below each of the above two lines: + <pre class="brush: js">console.log(randomNumber);</pre> + </li> + <li>Save and refresh, then play a few games — you'll see that <code>randomNumber</code> is equal to 1 at each point where it is logged to the console.</li> +</ol> + +<h3 id="Working_through_the_logic">Working through the logic</h3> + +<p>To fix this, let's consider how this line is working. First, we invoke <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></code>, which generates a random decimal number between 0 and 1, e.g. 0.5675493843.</p> + +<pre class="brush: js">Math.random()</pre> + +<p>Next, we pass the result of invoking <code>Math.random()</code> through <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor">Math.floor()</a></code>, which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:</p> + +<pre>Math.floor(Math.random()) + 1</pre> + +<p>Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:</p> + +<pre class="brush: js">Math.floor(Math.random()*100);</pre> + +<p>Hence us wanting to add 1, to give us a random number between 1 and 100:</p> + +<pre class="brush: js">Math.floor(Math.random()*100) + 1;</pre> + +<p>Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!</p> + +<h2 id="Other_common_errors">Other common errors</h2> + +<p>There are other common errors you'll come across in your code. This section highlights most of them.</p> + +<h3 id="SyntaxError_missing_before_statement">SyntaxError: missing ; before statement</h3> + +<p>This error generally means that you have missed a semi colon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the <code>checkGuess()</code> function:</p> + +<pre class="brush: js">var userGuess = Number(guessField.value);</pre> + +<p>to</p> + +<pre class="brush: js">var userGuess === Number(guessField.value);</pre> + +<p>It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (<code>=</code>) — which sets a variable to be equal to a value — with the strict equality operator (<code>===</code>), which tests whether one value is equal to another, and returns a <code>true</code>/<code>false</code> result.</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement">SyntaxError: missing ; before statement</a> reference page for more details about this error.</p> +</div> + +<h3 id="The_program_always_says_you've_won_regardless_of_the_guess_you_enter">The program always says you've won, regardless of the guess you enter</h3> + +<p>This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside <code>checkGuess()</code>:</p> + +<pre class="brush: js">if (userGuess === randomNumber) {</pre> + +<p>to</p> + +<pre class="brush: js">if (userGuess = randomNumber) {</pre> + +<p>the test would always return <code>true</code>, causing the program to report that the game has been won. Be careful!</p> + +<h3 id="SyntaxError_missing_)_after_argument_list">SyntaxError: missing ) after argument list</h3> + +<p>This one is pretty simple — it generally means that you've missed the closing parenthesis off the end of a function/method call.</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list">SyntaxError: missing ) after argument list</a> reference page for more details about this error.</p> +</div> + +<h3 id="SyntaxError_missing_after_property_id">SyntaxError: missing : after property id</h3> + +<p>This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing</p> + +<pre class="brush: js">function checkGuess() {</pre> + +<p>to</p> + +<pre class="brush: js">function checkGuess( {</pre> + +<p>This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!</p> + +<h3 id="SyntaxError_missing_after_function_body">SyntaxError: missing } after function body</h3> + +<p>This is easy — it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the <code>checkGuess()</code> function.</p> + +<h3 id="SyntaxError_expected_expression_got_'string'_or_SyntaxError_unterminated_string_literal">SyntaxError: expected expression, got '<em>string</em>' or SyntaxError: unterminated string literal</h3> + +<p>These errors generally mean that you've missed off a string value's opening or closing quote mark. In the first error above, <em>string</em> would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.</p> + +<p>For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!</p> + +<div class="note"> +<p><strong>Note</strong>: See our <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unexpected_token">SyntaxError: Unexpected token</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Errors/Unterminated_string_literal">SyntaxError: unterminated string literal</a> reference pages for more details about these errors.</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right earlier on in your learning journey.</p> + +<h2 id="See_also">See also</h2> + +<div> +<ul> + <li>There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail — see the <a href="/en-US/docs/Web/JavaScript/Reference/Errors">JavaScript error reference</a>.</li> + <li>If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask on the <a class="external external-icon" href="https://discourse.mozilla-community.org/t/learning-web-development-marking-guides-and-questions/16294">Learning Area Discourse thread</a>, or in the <a href="irc://irc.mozilla.org/mdn">#mdn</a> IRC channel on <a class="external external-icon" href="https://wiki.mozilla.org/IRC">Mozilla IRC</a>. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.</li> +</ul> +</div> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}</p> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> +</ul> diff --git a/files/it/learn/javascript/first_steps/index.html b/files/it/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..220f1f25c1 --- /dev/null +++ b/files/it/learn/javascript/first_steps/index.html @@ -0,0 +1,68 @@ +--- +title: JavaScript First Steps +slug: Learn/JavaScript/First_steps +tags: + - Arrays + - Article + - Assessment + - Beginner + - CodingScripting + - Guide + - JavaScript + - Landing + - Module + - NeedsTranslation + - Numbers + - Operators + - TopicStub + - Variables + - 'l10n:priority' + - maths + - strings +translation_of: Learn/JavaScript/First_steps +--- +<p class="summary">{{LearnSidebar}}Nel nostro primo modulo JavaScript, per prima cosa, rispondiamo ad alcune domande fondamentali come "cosa è JavaScript?", "a che cosa assomiglia?", e "cosa può fare?", prima di guidarti nella tua prima esperienza pratica di scrittura JavaScript. Dopodiché, discuteremo dettagliatamente, alcuni elementi chiave, come variabili, stringhe, numeri ed array.</p> + +<h2 id="Prerequisiti">Prerequisiti</h2> + +<p>Prima di iniziare questo modulo, non hai bisogno di alcuna precedente conoscenza di JavaScript, ma dovresti avere familiarità con HTML e CSS. Si consiglia di utilizzare i seguenti moduli prima di iniziare su JavaScript:</p> + +<ul> + <li><a href="/it/docs/Learn/Getting_started_with_the_web">Iniziare con il Web</a> (che include <a href="/it/docs/Getting_started_with_the_web/JavaScript_basics">un'introduzione Javascript realmente di base</a>)</li> + <li><a href="/it/docs/Learn/HTML/Introduction_to_HTML">Introduzione ad HTML</a>.</li> + <li><a href="/it/docs/Learn/CSS/Introduction_to_CSS">Introduzione a CSS</a>.</li> +</ul> + +<div class="note"> +<p><strong>Nota:</strong> Se stai lavorando su un computer/tablet/altro dispositivo dove non sei in grado di creare i tuoi files, potresti provare (la maggior parte) gli esempi di codice in un programma di codifica online come <a href="http://jsbin.com/">JSBin</a> o <a href="https://thimble.mozilla.org/">Thimble</a>.</p> +</div> + +<h2 id="Guide">Guide</h2> + +<dl> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/What_is_JavaScript">Cosa è JavaScript?</a></dt> + <dd>Benvenuto nel corso JavaScript per principianti di MDN! In questo primo articolo vedremo JavaScript da un livello alto, rispondendo a domande come "cosa è JavaScript?" e "cosa sta facendo?", e assicurandoci che tu sia a tuo agio con lo scopo di JavaScript.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/A_first_splash">Un primo tuffo in JavaScript</a></dt> + <dd>Ora che hai imparato qualcosa sulla teoria di JavaScript, e cosa puoi fare con esso, stiamo per fornirti un corso accelerato sulle caratteristiche di base di JavaScript attraverso un tutorial totalmente pratico. Qui costruirai un semplice gioco "Indovina il numero", passo dopo passo.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/What_went_wrong">Cosa è andato storto? Risoluzione dei problemi di JavaScript</a></dt> + <dd>Quando hai costruito il gioco "Indovina il numero" nel precedente articolo, potresti aver trovato che non funzionava. Nessuna paura - questo articolo mira a salvarti dallo strapparti i capelli su questi problemi fornendoti alcuni semplici consigli sul come trovare e correggere gli errori nei programmi JavaScript.</dd> + <dt><a href="/it/docs/Learn/JavaScript/First_steps/Variables">Memorizzare le informazioni ci cui hai bisogno - le Variabili</a></dt> + <dd>Dopo aver letto l'ultima coppia di articoli dovresti sapere cos'è JavaScript, cosa può fare per te, come usarlo con altre tecnologie web, e come le sue principali caratteristiche appaiono da un livello alto. In questo articolo andremo giù fino alle basi reali, guardando come lavorare con i blocchi di costruzione più semplici di JavaScript - Variabili.</dd> + <dt>Matemeatica di base in JavaScript - numeri e operatori</dt> + <dd>A questo punto del corso discuteremo matematica in JavaScript — come possiamo combinare operatori ed altre funzioni per manipolare con successo i numeri per fare i nostri bidding.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></dt> + <dd>Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></dt> + <dd>Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></dt> + <dd>In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.</dd> +</dl> + +<h2 id="Assessments">Assessments</h2> + +<p>The following assessment will test your understanding of the JavaScript basics covered in the guides above.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Silly story generator</a></dt> + <dd>In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!</dd> +</dl> diff --git a/files/it/learn/javascript/first_steps/variabili/index.html b/files/it/learn/javascript/first_steps/variabili/index.html new file mode 100644 index 0000000000..38da82e607 --- /dev/null +++ b/files/it/learn/javascript/first_steps/variabili/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 +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}</div> + +<p class="summary">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.</p> + +<table class="learn-box"> + <tbody> + <tr> + <th scope="row">Prerequisiti:</th> + <td>Nozioni di base di informatica, comprensione di base di HTML e CSS, comprensione di cosa sia JavaScript</td> + </tr> + <tr> + <th scope="row">Obiettivo:</th> + <td>Acquisire familiarità con le basi delle variabili JavaScript.</td> + </tr> + </tbody> +</table> + +<h2 id="Strumenti_di_cui_hai_bisogno">Strumenti di cui hai bisogno</h2> + +<p>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 <a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">Quali sono gli strumenti di sviluppo</a> del browser per ulteriori informazioni su come accedere a questo strumento).</p> + +<h2 id="Cosa_è_una_variabile">Cosa è una variabile?</h2> + +<p>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:</p> + +<pre class="brush: html notranslate"><button>Press me</button></pre> + +<pre class="brush: js notranslate">const button = document.querySelector('button'); + +button.onclick = function() { + let name = prompt('What is your name?'); + alert('Hello ' + name + ', nice to see you!'); +}</pre> + +<p>{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p> + +<p>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.</p> + +<p>Per capire perché questo è così utile, pensiamo a come scrivere questo esempio senza usare una variabile. Finirebbe per assomigliare a questo:</p> + +<pre class="example-bad notranslate">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 ...</pre> + +<p>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.</p> + +<p>Le variabili hanno senso e, man mano che impari di più su JavaScript, inizieranno a diventare una seconda natura.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Nota</strong>: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.</p> +</div> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13506/boxes.png" style="display: block; height: 436px; margin: 0px auto; width: 1052px;"></p> + +<h2 id="Dichiarare_una_variabile">Dichiarare una variabile</h2> + +<p>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:</p> + +<pre class="brush: js notranslate">let myName; +let myAge;</pre> + +<p>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.</p> + +<div class="note"> +<p><strong>Nota</strong>: 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.</p> +</div> + +<p>Puoi verificare se questi valori ora esistono nell'ambiente di esecuzione digitando solo il nome della variabile, ad es.</p> + +<pre class="brush: js notranslate">myName; +myAge;</pre> + +<p>Al momento non hanno valore; sono contenitori vuoti. Quando si immettono i nomi delle variabili, è necessario ottenere un valore <kbd>undefined</kbd>. Se non esistono, verrà visualizzato un messaggio di errore: "try typing in</p> + +<pre class="brush: js notranslate">scoobyDoo;</pre> + +<div class="note"> +<p><strong>Nota</strong>: 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.</p> +</div> + +<h2 id="Inizializzare_una_Variabile">Inizializzare una Variabile</h2> + +<p>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: </p> + +<pre class="brush: js notranslate">myName = 'Chris'; +myAge = 37;</pre> + +<p>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:</p> + +<pre class="brush: js notranslate">myName; +myAge;</pre> + +<p>Puoi dichiarare e inizializzare una variabile nello stesso tempo, come questo: </p> + +<pre class="brush: js notranslate">let myDog = 'Rover';</pre> + +<p>Questo è probabilmente ciò che farai la maggior parte del tempo, essendo il metodo più veloce rispetto alle due azioni separate. </p> + +<h2 id="Differenza_tra_var_e_let">Differenza tra var e let</h2> + +<p>A questo punto potresti pensare "perchè abbiamo bisogno di due keywords (parole chiavi) per definire le variabili?? Perchè avere <code>var</code> e <code>let</code>?".</p> + +<p>Le ragioni sono in qualche modo storiche. Ai tempi della creazione di JavaScript, c'era solo <code>var</code>. 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ì, <code>let</code> è stata creata nella moderna versione di JavaScript, una nuova keyword (parola chiave) per creare variabili che funzionano differentemente da <code>var</code>, risolvendo i suoi problemi nel processo.</p> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a>).</p> + +<p>Per iniziare, se scrivi un multilinea JavaScript che dichiara e inizializza una variabile, puoi effettivamente dichiarare una variabile con <code>var</code> dopo averla inizializzata funzionerà comunque. Per esempio:</p> + +<pre class="brush: js notranslate">myName = 'Chris'; + +function logName() { + console.log(myName); +} + +logName(); + +var myName;</pre> + +<div class="note"> +<p><strong>Nota: </strong> Questo non funziona quando digiti linee individuali in una JavaScript console, ma solo quando viene eseguita in linee multiple in un documento web. </p> +</div> + +<p>Questo lfunziona a causa di <strong>hoisting</strong> — leggi <a href="/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">var hoisting</a> per maggiori dettagli sull'argomento. </p> + +<p>Hoisting non funziona con <code>let</code>. Se cambiamo <code>var</code> a <code>let</code> 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.</p> + +<p>In secondo luogo, quando usi <code>var</code>, puoi dichiarare la stessa variabile tutte le volte che vuoi, ma con <code>let</code> non puoi. Quanto segue funzionerebbe: </p> + +<pre class="brush: js notranslate">var myName = 'Chris'; +var myName = 'Bob';</pre> + +<p>Ma il seguente darebbe un errore sulla seconda linea: </p> + +<pre class="brush: js notranslate">let myName = 'Chris'; +let myName = 'Bob';</pre> + +<p>Dovresti invece fare questo: </p> + +<pre class="brush: js notranslate">let myName = 'Chris'; +myName = 'Bob';</pre> + +<p>Ancora una volta, questa è un scelta linquistica più corretta. Non c'è motivo di ridichiarare le variabili: rende le cose più confuse.</p> + +<p>Per queste ragioni e altre, noi raccomandiamo di usare <code>let</code> il più possibile nel tuo codice, piuttosto che <code>var</code>. Non ci sono motivi per usare <code>var</code>, a meno che non sia necessario supportare vecchie versioni di Internet Explorer proprio con il tuo codice. ( <code>let</code> non è supportato fino fino alla versione 11, il moderno Windows Edge browser supporta bene <code>let</code>).</p> + +<div class="note"> +<p><strong>Nota: </strong> Attualmente stiamo aggiornando il corso per usare più <code>let</code> piuttosto che <code>var</code>. Abbi pazienza con noi!</p> +</div> + +<h2 id="Aggiornare_una_variabile">Aggiornare una variabile</h2> + +<p>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: </p> + +<pre class="brush: js notranslate">myName = 'Bob'; +myAge = 40;</pre> + +<h3 id="Regole_di_denominazione_delle_variabili">Regole di denominazione delle variabili</h3> + +<p>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 ( _ ).</p> + +<ul> + <li>Non dovresti usare altri caratteri perchè possono causare errori o essere difficili da capire per un pubblico internazionale. </li> + <li>Non usare l'underscores all'inizio di un nome di una variabile — questo è usato in alcuni costrutti JavaScript per dire cose specifiche, quindi può generare confusione. </li> + <li>Non usare numeri all'inizio di una variabile. Questo non è permesso e causa un errore. </li> + <li>Una convezione sicura alla quale attenersi si chiama <a href="https://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms">"notazione a cammello"</a>, dove per unire più parole, si usa il minuscolo per la prima parola e la lettera maiuscola per le seguenti parole. Abbiamo usato questo per i nomi delle variabili in questo articolo. (es: myName)</li> + <li>Creare i nomi delle variabili intuitivi, in modo che descrivano i dati che contengono. Non usare singole lettere / numeri, o lunghe frasi.</li> + <li>Le variabili sono case sensitive — così <code>myage</code> è differente da <code>myAge</code>.</li> + <li>Ultimo punto: devi evitare di usare parole riservate a JavaScript come nomi delle variabili — con questo intendiamo le parole che compongono la sintassi effettiva di JavaScript! Così, non puoi usare parole come <code>var</code>, <code>function</code>, <code>let</code>, e <code>for</code> come nomi di variabili. I browsers li riconoscono come elementi differenti di codice, e così danno errore. </li> +</ul> + +<div class="note"> +<p><strong>Nota</strong>: Puoi trovare un elenco abbastanza completo di parole riservate da evitare a <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">Lexical grammar — keywords</a>.</p> +</div> + +<p>Esempi di nomi corretti: </p> + +<pre class="example-good notranslate">age +myAge +init +initialColor +finalOutputValue +audio1 +audio2</pre> + +<p>Esempi di nomi errati: </p> + +<pre class="example-bad notranslate">1 +a +_12 +myage +MYAGE +var +Document +skjfndskjfnbdskjfb +thisisareallylongstupidvariablenameman</pre> + +<p>Esempi di nomi soggetti a errori: </p> + +<pre class="example-invalid notranslate">var +Document +</pre> + +<p>Prova a creare qualche altra variabile ora, tenendo presente le indicazioni sopra riportate. </p> + +<h2 id="Tipi_di_Variabili">Tipi di Variabili</h2> + +<p>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.</p> + +<p>Finora abbiamo esaminato i primi due, ma che ne sono altri. </p> + +<h3 id="Numeri">Numeri</h3> + +<p>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:</p> + +<pre class="brush: js notranslate">let myAge = 17;</pre> + +<h3 id="Stringhe">Stringhe</h3> + +<p>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. </p> + +<pre class="brush: js notranslate">let dolphinGoodbye = 'So long and thanks for all the fish';</pre> + +<h3 id="Booleani">Booleani</h3> + +<p>I booleani sono dei valori vero/falso — possono avere due valori <code>true</code> o <code>false</code>. Questi sono generalmente usati per testare delle condizioni, dopo di che il codice viene eseguito come appropriato . Ad esempio, un semplice caso sarebbe:</p> + +<pre class="brush: js notranslate">let iAmAlive = true;</pre> + +<p>Considerando che in realtà sarebbe usato più così:</p> + +<pre class="brush: js notranslate">let test = 6 < 3;</pre> + +<p>Questo sta usando l'operatore "minore di" (<code><</code>) per verificare se 6 è minore di 3. Come ci si potrebbe aspettare, restituisce <code>false</code>, perché 6 non è inferiore a 3! Imparerai molto di più su questi operatori più avanti nel corso.</p> + +<h3 id="Arrays">Arrays</h3> + +<p>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:</p> + +<pre class="brush: js notranslate">let myNameArray = ['Chris', 'Bob', 'Jim']; +let myNumberArray = [10, 15, 40];</pre> + +<p>Una volta che gli arrays sono definiti, è possibile accedere a ciascun valore in base alla posizione all'interno dell'array. Prova queste linee:</p> + +<pre class="brush: js notranslate">myNameArray[0]; // should return 'Chris' +myNumberArray[2]; // should return 40</pre> + +<p>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.</p> + +<p>Puoi imparare molto sugli arrays in <a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">un futuro articolo</a>.</p> + +<h3 id="Oggetti">Oggetti</h3> + +<p>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<br> + e altro ancora.</p> + +<p>Prova a inserire il seguente codice nella tua console:</p> + +<pre class="brush: js notranslate">let dog = { name : 'Spot', breed : 'Dalmatian' };</pre> + +<p>Per recuperare le informazioni archiviate nell'oggetto, è possibile utilizzare la seguente sintassi:</p> + +<pre class="brush: js notranslate">dog.name</pre> + +<p>Per ora non esamineremo più gli oggetti: puoi saperne di più su quelli in un <a href="/en-US/docs/Learn/JavaScript/Objects"> modulo futuro.</a></p> + +<h2 id="Tipizzazione_dinamica">Tipizzazione dinamica</h2> + +<p>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.).</p> + +<p>Ad esempio, se dichiari una variabile e le assegni un valore racchiuso tra virgolette, il browser considera la variabile come una stringa:</p> + +<pre class="brush: js notranslate">let myString = 'Hello';</pre> + +<p>Anche se il valore contiene numeri, è comunque una stringa, quindi fai attenzione:</p> + +<pre class="brush: js notranslate">let myNumber = '500'; // oops, questa è ancora una stringa +typeof myNumber; +myNumber = 500; // molto meglio - adesso questo è un numero +typeof myNumber;</pre> + +<p>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 <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code>- questo restituisce il tipo di dati della variabile che scrivi dopo. La prima volta che viene chiamato, dovrebbe restituire <code>string</code>, poiché a quel punto la variabile <code>myNumber</code> contiene una stringa, <code>'500'</code>.<br> + Dai un'occhiata e vedi cosa restituisce la seconda volta che lo chiami.</p> + +<h2 id="Costanti_in_JavaScript">Costanti in JavaScript</h2> + +<p>Molti linguaggi di programmazione hanno il concetto di <em>costante</em> - 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).</p> + +<p>All'inizio di JavaScript, le costanti non esistevano. Nel moderno JavaScript, abbiamo la parola chiave <code>const</code>, che ci consente di memorizzare valori che non possono mai essere modificati:</p> + +<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">; +const hoursInDay = 24;</span></span></span></span></pre> + +<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number"><code>const</code> lavora esattamente come <code>let</code>, eccetto che non puoi dare a<code>const</code> un nuovo valore. Nell'esempio seguente, la seconda linea genera un errore:</span></span></span></span></p> + +<pre class="brush: js notranslate">const daysInWeek = 7<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-number">; +daysInWeek = 8;</span></span></span></span></pre> + +<h2 id="Sommario">Sommario </h2> + +<p>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.</p> + +<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "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">The 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> |