diff options
Diffstat (limited to 'files/de/learn/javascript/first_steps/variables/index.html')
-rw-r--r-- | files/de/learn/javascript/first_steps/variables/index.html | 386 |
1 files changed, 0 insertions, 386 deletions
diff --git a/files/de/learn/javascript/first_steps/variables/index.html b/files/de/learn/javascript/first_steps/variables/index.html deleted file mode 100644 index d8906f7d02..0000000000 --- a/files/de/learn/javascript/first_steps/variables/index.html +++ /dev/null @@ -1,386 +0,0 @@ ---- -title: Speichern der benötigten Informationen — Variablen -slug: Learn/JavaScript/First_steps/Variables -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">After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.</p> - -<table class="learn-box"> - <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 familiarity with the basics of JavaScript variables.</td> - </tr> - </tbody> -</table> - -<h2 id="Tools_you_need">Tools you need</h2> - -<p>Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">What are browser developer tools</a> for more information on how to access this tool).</p> - -<p>However, we have also provided a simple JavaScript console embedded in the page below for you to enter this code into, in case you are not using a browser with a JavaScript console easily available, or find an in-page console more comfortable.</p> - -<h2 id="Was_ist_eine_Variable">Was ist eine Variable?</h2> - -<p>Eine Variable ist ein Behälter für einen Wert, wie z.B. eine Zahl, welche wir vielleicht für eine Summe benötigen, oder eine Zeichenkette die wir für einen Teil eines Satzes brauchen. Eine Besonderheit von Variablen ist, dass ihr Wert verändert werden kann. Hier ein Beispiel:</p> - -<pre class="brush: html"><button>Press me</button></pre> - -<pre class="brush: js">var button = document.querySelector('button'); - -button.onclick = function() { - var name = prompt('Wie heißt du?'); - alert('Hallo ' + name + ', schön dich zu sehen!'); -}</pre> - -<p>{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p> - -<p>In diesem Beispiel werden beim Drücken des Buttons einige Zeilen Code ausgeführt. Die erste Zeile zeigt eine Box an, welche den Leser nach seinem Namen fragt und den Wert anschließend in einer Variable abspeichert. Die zweite Zeile zeigt eine Willkommensnachricht, die den Namen enthält, welcher dem Wert der Variable entnommen wird.</p> - -<p>Um zu verstehen, warum das so nützlich ist, überlegen wir mal, wie wir das Beispiel ohne eine Variable schreiben würden. Es würde etwa so aussehen:</p> - -<pre class="example-bad">var name = prompt('Wie heißt du?'); - -if (name === 'Adam') { - alert('Hallo Adam, schön dich zu sehen!'); -} else if (name === 'Alan') { - alert('Hallo Alan, schön dich zu sehen!'); -} else if (name === 'Bella') { - alert('Hallo Bella, schön dich zu sehen!'); -} else if (name === 'Bianca') { - alert('Hallo Bianca, schön dich zu sehen!'); -} else if (name === 'Chris') { - alert('Hallo Chris, schön dich zu sehen!'); -} - -// ... und so weiter ...</pre> - -<p>You may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for that name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices.</p> - -<p>Variables just make sense, and as you learn more about JavaScript they will start to become second nature.</p> - -<p>Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.</p> - -<p><u><strong>Note that we say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.</strong></u></p> - -<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="Eine_Variable_deklarieren">Eine Variable deklarieren</h2> - -<p>To use a variable you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword var followed by the name you want to call your variable:</p> - -<pre class="brush: js">var myName; -var myAge;</pre> - -<p>Here we're creating two variables called <code>myName</code> and <code>myAge</code>. Try typing these lines in now in your web browser's console, or in the below console (You can <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">open this console</a> in a separate tab or window if you'd prefer that). After that, try creating a variable (or two) with your own name choices.</p> - -<div class="hidden"> -<h6 id="Hidden_code">Hidden code</h6> - -<pre class="brush: html"><!DOCTYPE html> -<html> - <head> - <meta charset="utf-8"> - <title>JavaScript console</title> - <style> - * { - box-sizing: border-box; - } - - html { - background-color: #0C323D; - color: #809089; - font-family: monospace; - } - - body { - max-width: 700px; - } - - p { - margin: 0; - width: 1%; - padding: 0 1%; - font-size: 16px; - line-height: 1.5; - float: left; - } - - .input p { - margin-right: 1%; - } - - .output p { - width: 100%; - } - - .input input { - width: 96%; - float: left; - border: none; - font-size: 16px; - line-height: 1.5; - font-family: monospace; - padding: 0; - background: #0C323D; - color: #809089; - } - - div { - clear: both; - } - - </style> - </head> - <body> - - - </body> - - <script> - var geval = eval; - function createInput() { - var inputDiv = document.createElement('div'); - var inputPara = document.createElement('p'); - var inputForm = document.createElement('input'); - - inputDiv.setAttribute('class','input'); - inputPara.textContent = '>'; - inputDiv.appendChild(inputPara); - inputDiv.appendChild(inputForm); - document.body.appendChild(inputDiv); - - if(document.querySelectorAll('div').length > 1) { - inputForm.focus(); - } - - inputForm.addEventListener('change', executeCode); - } - - function executeCode(e) { - try { - var result = geval(e.target.value); - } catch(e) { - var result = 'error — ' + e.message; - } - - var outputDiv = document.createElement('div'); - var outputPara = document.createElement('p'); - - outputDiv.setAttribute('class','output'); - outputPara.textContent = 'Result: ' + result; - outputDiv.appendChild(outputPara); - document.body.appendChild(outputDiv); - - e.target.disabled = true; - e.target.parentNode.style.opacity = '0.5'; - - createInput() - } - - createInput(); - - </script> -</html></pre> -</div> - -<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p> - -<div class="note"> -<p><strong>Note</strong>: In JavaScript, all code instructions should end with a semi-colon (<code>;</code>) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.</p> -</div> - -<p>You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.</p> - -<pre class="brush: js">myName; -myAge;</pre> - -<p>They currently have no value; they are empty containers. When you enter the variable names, you should get a value of <code>undefined</code> returned. If they don't exist, you'll get an error message — try typing in</p> - -<pre class="brush: js">scoobyDoo;</pre> - -<div class="note"> -<p><strong>Note</strong>: Don't confuse a variable that exists but has no value defined with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it.</p> -</div> - -<h2 id="Eine_Variable_initialisieren">Eine Variable initialisieren</h2> - -<p>Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (<code>=</code>), followed by the value you want to give it. For example:</p> - -<pre class="brush: js">myName = 'Chris'; -myAge = 37;</pre> - -<p>Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by simply typing their name into the console — try these again:</p> - -<pre class="brush: js">myName; -myAge;</pre> - -<p>You can declare and initialize a variable at the same time, like this:</p> - -<pre class="brush: js">var myName = 'Chris';</pre> - -<p>This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.</p> - -<div class="note"> -<p><strong>Note</strong>: If you write a multiline JavaScript program that declares and initializes a variable, you can actually declare it after you initialize it and it will still work. This is because variable declarations are generally done first before the rest of the code is executed. This is called <strong>hoisting</strong> — read <a href="/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">var hoisting</a> for more detail on the subject.</p> -</div> - -<h2 id="Eine_Variable_aktualisieren">Eine Variable aktualisieren</h2> - -<p>Once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. Try entering the following lines into your console:</p> - -<pre class="brush: js">myName = 'Bob'; -myAge = 40;</pre> - -<h3 id="An_aside_on_variable_naming_rules">An aside on variable naming rules</h3> - -<p>You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.</p> - -<ul> - <li>You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.</li> - <li>Don't use underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.</li> - <li>Don't use numbers at the start of variables. This isn't allowed and will cause an error.</li> - <li>A safe convention to stick to is so-called <a href="https://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms">"lower camel case"</a>, where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.</li> - <li>Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.</li> - <li>Variables are case sensitive — so <code>myage</code> is a different variable to <code>myAge</code>.</li> - <li>One last point — you also need to avoid using JavaScript reserved words as your variable names — by this, we mean the words that make up the actual syntax of JavaScript! So you can't use words like <code>var</code>, <code>function</code>, <code>let</code>, and <code>for</code> as variable names. Browsers will recognize them as different code items, and so you'll get errors.</li> -</ul> - -<div class="note"> -<p><strong>Note</strong>: You can find a fairly complete list of reserved keywords to avoid at <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">Lexical grammar — keywords</a>.</p> -</div> - -<p>Good name examples:</p> - -<pre class="example-good">age -myAge -init -initialColor -finalOutputValue -audio1 -audio2</pre> - -<p>Bad name examples:</p> - -<pre class="example-bad">1 -a -_12 -myage -MYAGE -var -Document -skjfndskjfnbdskjfb -thisisareallylongstupidvariablenameman</pre> - -<p>Error-prone name examples:</p> - -<pre class="example-invalid">var -Document -</pre> - -<p>Try creating a few more variables now, with the above guidance in mind.</p> - -<h2 id="Typen_von_Variablen">Typen von Variablen</h2> - -<p>There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.</p> - -<p>So far we've looked at the first two, but there are others.</p> - -<h3 id="Numbers">Numbers</h3> - -<p>You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:</p> - -<pre class="brush: js">var myAge = 17;</pre> - -<h3 id="Strings">Strings</h3> - -<p>Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks, otherwise, JavaScript will try to interpret it as another variable name.</p> - -<pre class="brush: js">var dolphinGoodbye = 'So long and thanks for all the fish';</pre> - -<h3 id="Booleans">Booleans</h3> - -<p>Booleans are true/false values — they can have two values, <code>true</code> or <code>false</code>. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:</p> - -<pre class="brush: js">var iAmAlive = true;</pre> - -<p>Whereas in reality it would be used more like this:</p> - -<pre class="brush: js">var test = 6 < 3;</pre> - -<p>This is using the "less than" operator (<code><</code>) to test whether 6 is less than 3. As you might expect, it will return <code>false</code>, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.</p> - -<h3 id="Arrays">Arrays</h3> - -<p>An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:</p> - -<pre class="brush: js">var myNameArray = ['Chris', 'Bob', 'Jim']; -var myNumberArray = [10,15,40];</pre> - -<p>Once these arrays are defined, you can access each value by their location within the array. Try these lines:</p> - -<pre class="brush: js">myNameArray[0]; // should return 'Chris' -myNumberArray[2]; // should return 40</pre> - -<p>The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.</p> - -<p>You'll learn a lot more about arrays in a future article.</p> - -<h3 id="Objects">Objects</h3> - -<p>In programming, an object is a structure of the code that models a real-life object. You can have a simple object that represents a car park and contains information about its width and length, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.</p> - -<p>Try entering the following line into your console:</p> - -<pre class="brush: js">var dog = { name : 'Spot', breed : 'Dalmatian' };</pre> - -<p>To retrieve the information stored in the object, you can use the following syntax:</p> - -<pre class="brush: js">dog.name</pre> - -<p>We won't be looking at objects any more for now — you can learn more about those in a future module.</p> - -<h2 id="Dynamic_typing">Dynamic typing</h2> - -<p>JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (e.g. numbers, strings, arrays, etc).</p> - -<p>For example, if you declare a variable and give it a value encapsulated in quotes, the browser will treat the variable as a string:</p> - -<pre class="brush: js">var myString = 'Hello';</pre> - -<p>It will still be a string, even if it contains numbers, so be careful:</p> - -<pre class="brush: js">var myNumber = '500'; // oops, this is still a string -typeof myNumber; -myNumber = 500; // much better — now this is a number -typeof myNumber;</pre> - -<p>Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called <code>typeof</code> — this returns the data type of the variable you pass into it. The first time it is called, it should return <code>string</code>, as at that point the <code>myNumber</code> variable contains a string, <code>'500'</code>. Have a look and see what it returns the second time you call it.</p> - -<h2 id="Zusammenfassung">Zusammenfassung</h2> - -<p>By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math 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> |