Skip to content

JavaScript specials #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
190 changes: 95 additions & 95 deletions 1-js/02-first-steps/18-javascript-specials/article.md
Original file line number Diff line number Diff line change
@@ -1,156 +1,156 @@
# JavaScript specials
# JavaScript Besonderheiten

This chapter briefly recaps the features of JavaScript that we've learned by now, paying special attention to subtle moments.
Dieses Kapitel wiederholt kurz die Features von JavaScript, die wir bis jetzt gelernt haben, mit besonderer Aufmerksamkeit auf die subtilen Momente.

## Code structure
## Code Struktur

Statements are delimited with a semicolon:
Anweisungen werden mit einem Semikolon getrennt:

```js run no-beautify
alert('Hello'); alert('World');
alert('Hallo'); alert('Welt');
```

Usually, a line-break is also treated as a delimiter, so that would also work:
Normalerweise wird ein Zeilenumbruch ebenfalls als Trennzeichen behandelt, so dass auch das funktioniert:

```js run no-beautify
alert('Hello')
alert('World')
alert('Hallo')
alert('Welt')
```

That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance:
Das wird "Automatisches Einfügen von Semikolons" genannt. Manchmal funktioniert das nicht, zum Beispiel:

```js run
alert("There will be an error after this message")
alert("Es wird einen Fehler nach dieser Nachricht geben")

[1, 2].forEach(alert)
```

Most codestyle guides agree that we should put a semicolon after each statement.
Die Meisten Codestil-Leitfäden stimmen darin überein, dass wir ein Semikolon nach jeder Anweisung setzen sollten.

Semicolons are not required after code blocks `{...}` and syntax constructs with them like loops:
Semikolons sind nach Codeblöcken und Syntaxkonstrukten mit geschweiften Klammern `{...}`, wie z.B. Schleifen, nicht erforderlich:

```js
function f() {
// no semicolon needed after function declaration
// kein Semikolon nach der Funktionsdeklaration erforderlich
}

for(;;) {
// no semicolon needed after the loop
// kein Semikolon nach der Schleife erforderlich
}
```

...But even if we can put an "extra" semicolon somewhere, that's not an error. It will be ignored.
...Aber selbst wenn wir irgendwo ein "zusätzliches" Semikolon setzen, ist das kein Fehler. Es wird ignoriert.

More in: <info:structure>.
Mehr in: <info:structure>.

## Strict mode
## Strikter Modus

To fully enable all features of modern JavaScript, we should start scripts with `"use strict"`.
Um alle Funktionen des modernen JavaScripts zu ermöglichen, sollten wir Skripte mit `"use strict"` beginnen.

```js
'use strict';

...
```

The directive must be at the top of a script or at the beginning of a function body.
Die Direktive muss am Anfang eines Skripts oder am Anfang eines Funktionsrumpfes stehen.

Without `"use strict"`, everything still works, but some features behave in the old-fashion, "compatible" way. We'd generally prefer the modern behavior.
Ohne `"use strict"` funktioniert alles weiterhin, aber einige Funktionen verhalten sich in der alten, "kompatiblen" Weise. Wir würden im Allgemeinen das moderne Verhalten bevorzugen.

Some modern features of the language (like classes that we'll study in the future) enable strict mode implicitly.
Einige moderne Features der Sprache (wie Klassen, die wir in der Zukunft behandeln) aktivieren den strikten Modus implizit.

More in: <info:strict-mode>.
Mehr in: <info:strict-mode>.

## Variables
## Variablen

Can be declared using:
Können deklariert werden mit:

- `let`
- `const` (constant, can't be changed)
- `var` (old-style, will see later)
- `const` (Konstante, kann icht geändert werden)
- `var` (altmodisch, sehen wir später)

A variable name can include:
- Letters and digits, but the first character may not be a digit.
- Characters `$` and `_` are normal, on par with letters.
- Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used.
Ein Variablenname kann folgendes enthalten:
- Buchstaben und Ziffern, aber das erste Zeichen darf keine Ziffer sein.
- Zeichen `$` und `_` sind normal, und auf gleicher Ebene mit Buchstaben.
- Nichtlateinische Alphabete und Hieroglyphen sind ebenfalls erlaubt, aber werden für gewöhnlich nicht genutzt.

Variables are dynamically typed. They can store any value:
Variablen sind dynamisch typisiert. Sie können einen beliebigen Wert beinhalten:

```js
let x = 5;
x = "John";
```

There are 8 data types:
Es gibt 8 Datentypen:

- `number` for both floating-point and integer numbers,
- `bigint` for integer numbers of arbitrary length,
- `string` for strings,
- `boolean` for logical values: `true/false`,
- `null` -- a type with a single value `null`, meaning "empty" or "does not exist",
- `undefined` -- a type with a single value `undefined`, meaning "not assigned",
- `object` and `symbol` -- for complex data structures and unique identifiers, we haven't learnt them yet.
- `number` für Gleitkommazahlen und Ganzzahlen,
- `bigint` für Ganzzahlen beliebiger Länge,
- `string` für Zeichenfolgen,
- `boolean` Für logische Werte: `true/false`,
- `null` -- ein Typ mit einem einzigen Wert `null`, der "leer" oder "existiert nicht" bedeutet,
- `undefined` -- ein Typ mit einem einzigen Wert `undefined`, der "nicht zugewiesen" bedeutet,
- `object` und `symbol` -- für komplexe Datenstrukturen und eindeutige Bezeichner, die wir noch nicht erlernt haben.

The `typeof` operator returns the type for a value, with two exceptions:
Der `typeof`-Operator gibt den Typ eines Wertes zurück, mit zwei Ausnahmen:
```js
typeof null == "object" // error in the language
typeof function(){} == "function" // functions are treated specially
typeof null == "object" // Fehler in der Sprache
typeof function(){} == "function" // Funktionen werden gesondert behandelt
```

More in: <info:variables> and <info:types>.
Mehr in: <info:variables> und <info:types>.

## Interaction
## Interaktion

We're using a browser as a working environment, so basic UI functions will be:
Wir benutzen einen Browser als Arbeitsumgebung, also sind grundlegende UI-Funktionen:

[`prompt(question, [default])`](mdn:api/Window/prompt)
: Ask a `question`, and return either what the visitor entered or `null` if they clicked "cancel".
: Stell eine `Frage` und gib zurück was die Besucher eingegeben haben oder `null` wenn sie auf "Abbrechen" geklickt haben.

[`confirm(question)`](mdn:api/Window/confirm)
: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`.
: Stell eine `Frage` und schlag die Auswahlt zwischen OK und Abbrechen vor. Die Auswahl wird als `true/false` zurückgegeben.

[`alert(message)`](mdn:api/Window/alert)
: Output a `message`.
: Ausgabe einer `Nachricht`.

All these functions are *modal*, they pause the code execution and prevent the visitor from interacting with the page until they answer.
Alle diese Funktionen sind *modal*, sie pausieren das Ausführen des Codes und verhindern, dass die Benutzer mit der Seite interagieren bis sie antworten.

For instance:
Zum Beispiel:

```js run
let userName = prompt("Your name?", "Alice");
let isTeaWanted = confirm("Do you want some tea?");
let userName = prompt("Dein Name?", "Alice");
let isTeaWanted = confirm("Möchtest du etwas Tee?");

alert( "Visitor: " + userName ); // Alice
alert( "Tea wanted: " + isTeaWanted ); // true
alert( "Besucher: " + userName ); // Alice
alert( "Tee gewünscht: " + isTeaWanted ); // true
```

More in: <info:alert-prompt-confirm>.
Mehr in: <info:alert-prompt-confirm>.

## Operators
## Operatoren

JavaScript supports the following operators:
JavaScript unterstützt folgende Operatoren:

Arithmetical
: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number.
Arithmetisch
: Gewöhnlich: `* + - /`, ebenfalls `%` für den Rest und `**` für die Potenz einer Zahl.

The binary plus `+` concatenates strings. And if any of the operands is a string, the other one is converted to string too:
Das binäre Plus `+` setzt Zeichenketten zusammen. Und wenn einer der Operanden eine Zeichenkette ist, wird der andere auch in eine Zeichenkette konvertiert:

```js run
alert( '1' + 2 ); // '12', string
alert( 1 + '2' ); // '12', string
```

Assignments
: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
Zuweisungen
: Es gibt eine einfache Zuweisung: `a = b` und kombinierte `a *= 2`.

Bitwise
: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Guide/Expressions_and_Operators#Bitwise) when they are needed.

Conditional
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
Bedingt
: Der einzige Operator mit drei Parametern: `cond ? resultA : resultB`. Wenn `cond` wahr ist, gib `resultA` zurück, andernfalls `resultB`.

Logical operators
: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped (not necessary `true`/`false`). Logical NOT `!` converts the operand to boolean type and returns the inverse value.
Logische Operatoren
: Logisches UND `&&` und ODER `||` führen Kurzzschlussauswertungen aus und dann geben sie den Wert zurück wo sie angehalten sind (nicht unbedingt `true`/`false`). Logisches NICHT `!` Konvertiert den Operand in einen bool'schen Typ und gibt den umgekehrten Wert zurück.

Nullish coalescing operator
: The `??` operator provides a way to choose a defined value from a list of variables. The result of `a ?? b` is `a` unless it's `null/undefined`, then `b`.
Expand All @@ -163,22 +163,22 @@ Comparisons
alert( 0 == '' ); // true
```

Other comparisons convert to a number as well.
Andere Vergleiche konvertieren ebenfalls in eine Zahl.

The strict equality operator `===` doesn't do the conversion: different types always mean different values for it.
Der strikte Gleichheitsoperator `===` führt diese Konversion nicht durch: unterschiedliche Typen bedeuten immer unterschieldiche Werte dafür.

Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else.
Werte `null` und `undefined` sind besonders: sie sind gleich `==` zueinander und nicht gleich zu etwas anderem.

Greater/less comparisons compare strings character-by-character, other types are converted to a number.
Größer/kleiner-Vergleiche vergleichen Zeichenketten zeichenweise, andere Typen werden in eine Zahl umgewandelt.

Other operators
: There are few others, like a comma operator.
Andere Operatoren
: Es gibt einige andere, wie den Komma-Operator.

More in: <info:operators>, <info:comparison>, <info:logical-operators>, <info:nullish-coalescing-operator>.

## Loops
## Schleifen

- We covered 3 types of loops:
- Wir haben 3 Typen von Schleifen behandelt:

```js
// 1
Expand All @@ -197,43 +197,43 @@ More in: <info:operators>, <info:comparison>, <info:logical-operators>, <info:nu
}
```

- The variable declared in `for(let...)` loop is visible only inside the loop. But we can also omit `let` and reuse an existing variable.
- Directives `break/continue` allow to exit the whole loop/current iteration. Use labels to break nested loops.
- Die Variable die in der `for(let...)`-Schleife deklariert wurde, ist nur in der Schleife sichtbar. Aber wir können `let` auch weglassen und eine vorhandene Variable wiederverwenden.
- Direktiven `break/continue` ermöglichen es die ganze Schleife/aktuelle Iteration zu verlassen. Benutze Labels, um verschachtelte Schleifen abzubrechen.

Details in: <info:while-for>.

Later we'll study more types of loops to deal with objects.
Später werden wir weitere Arten von Schleifen untersuchen, um mit Objekten zu arbeiten.

## The "switch" construct
## Das "switch" Konstrukt

The "switch" construct can replace multiple `if` checks. It uses `===` (strict equality) for comparisons.
Das "switch" Konstrukt kann mehrere `if`-Abfragen ersetzen. Es verwendet `===` (strikte Gleichheit) für Vergleiche.

For instance:
Zum Beispiel:

```js run
let age = prompt('Your age?', 18);
let age = prompt('Dein Alter?', 18);

switch (age) {
case 18:
alert("Won't work"); // the result of prompt is a string, not a number
break;

case "18":
alert("This works!");
alert("Das funktioniert!");
break;

default:
alert("Any value not equal to one above");
alert("Ein beliegibert Wert ungleich eines der oberen");
}
```

Details in: <info:switch>.

## Functions
## Funktionen

We covered three ways to create a function in JavaScript:
Wir betrachteten drei Möglichkeiten zum Erstellen einer Funktion in JavaScript:

1. Function Declaration: the function in the main code flow
1. Funktionsdeklaration: die Funktion im Hauptcodeablauf

```js
function sum(a, b) {
Expand All @@ -243,7 +243,7 @@ We covered three ways to create a function in JavaScript:
}
```

2. Function Expression: the function in the context of an expression
2. Funktionsausdruck: die Funktion im Kontext eines Ausdrucks

```js
let sum = function(a, b) {
Expand All @@ -253,22 +253,22 @@ We covered three ways to create a function in JavaScript:
};
```

3. Arrow functions:
3. Pfeilfunktionen:

```js
// expression on the right side
let sum = (a, b) => a + b;

// or multi-line syntax with { ... }, need return here:
// oder mehrzeilige Syntax mit { ... }, benötigt hier return:
let sum = (a, b) => {
// ...
return a + b;
}

// without arguments
let sayHi = () => alert("Hello");
// ohne Argumente
let sayHi = () => alert("Hallo");

// with a single argument
// mit einem einzigen Argument
let double = n => n * 2;
```

Expand All @@ -277,8 +277,8 @@ We covered three ways to create a function in JavaScript:
- Parameters can have default values: `function sum(a = 1, b = 2) {...}`.
- Functions always return something. If there's no `return` statement, then the result is `undefined`.

Details: see <info:function-basics>, <info:arrow-functions-basics>.
Details: siehe <info:function-basics>, <info:arrow-functions-basics>.

## More to come
## Da kommt noch mehr

That was a brief list of JavaScript features. As of now we've studied only basics. Further in the tutorial you'll find more specials and advanced features of JavaScript.
Das war eine kurze Zusammenfassung von JavaScript-Funktionen. Bis jetzt haben wir nur die Grundlagen kennengelernt. Im weiteren Verlauf des Tutorials findest du weitere Besonderheiten und fortgeschrittene Funktionen von JavaScript.