Anfänger142025-01-15

JavaScript Operators - Arithmetik, Vergleiche & Logik

Lerne alle JavaScript Operators: Arithmetische (+, -, *, /), Vergleichs (==, ===, <, >), Logische (&&, ||, !), Ternary und mehr.

#javascript#operators#arithmetic#comparison#logical

JavaScript Operators

Operators führen Operationen auf Werten aus. Wie ein Taschenrechner für deinen Code!

Arithmetic Operators - Rechenoperationen

Grundrechenarten:

Arithmetische Operators
// Addition
const summe = 5 + 3;
console.log(summe);  // 8

// Subtraktion
const differenz = 10 - 4;
console.log(differenz);  // 6

// Multiplikation
const produkt = 6 * 7;
console.log(produkt);  // 42

// Division
const quotient = 20 / 5;
console.log(quotient);  // 4

// Modulo (Rest)
const rest = 10 % 3;
console.log(rest);  // 1

// Potenz (ES7)
const potenz = 2 ** 3;
console.log(potenz);  // 8 (2³)

Modulo % - Der Rest-Operator

Modulo verstehen
// Rest bei Division
console.log(10 % 3);  // 1 (10 / 3 = 3 Rest 1)
console.log(15 % 4);  // 3 (15 / 4 = 3 Rest 3)
console.log(20 % 5);  // 0 (20 / 5 = 4 Rest 0)

// Gerade oder ungerade?
const zahl = 7;
if (zahl % 2 === 0) {
    console.log('Gerade');
} else {
    console.log('Ungerade');  // Wird ausgegeben
}

// Jedes n-te Element
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let i = 0; i < array.length; i++) {
    if (i % 3 === 0) {
        console.log(array[i]);  // 0, 3, 6, 9
    }
}

📝 Quiz

Was ist das Ergebnis von 2 + 3 * 4?

Assignment Operators - Zuweisungen

Zuweisung mit Berechnung
let x = 10;

// Addition
x += 5;  // x = x + 5
console.log(x);  // 15

// Subtraktion
x -= 3;  // x = x - 3
console.log(x);  // 12

// Multiplikation
x *= 2;  // x = x * 2
console.log(x);  // 24

// Division
x /= 4;  // x = x / 4
console.log(x);  // 6

// Modulo
x %= 4;  // x = x % 4
console.log(x);  // 2

// Potenz
x **= 3;  // x = x ** 3
console.log(x);  // 8

Increment & Decrement

++ und --
let count = 0;

// Increment (erhöhen um 1)
count++;  // count = count + 1
console.log(count);  // 1

count++;
console.log(count);  // 2

// Decrement (verringern um 1)
count--;  // count = count - 1
console.log(count);  // 1

// Unterschied: Prefix vs Postfix
let a = 5;
console.log(a++);  // 5 (erst nutzen, dann erhöhen)
console.log(a);    // 6

let b = 5;
console.log(++b);  // 6 (erst erhöhen, dann nutzen)
console.log(b);    // 6

Best Practice: Nutze ++ / -- in eigener Zeile (vermeide in Expressions)

📝 Quiz

Was ist der Unterschied zwischen a++ und ++a?

Comparison Operators - Vergleiche

Vergleichs-Operators
const a = 10;
const b = 5;

// Gleich (loose)
console.log(5 == '5');   // true (konvertiert!)

// Gleich (strict) - NUTZE DIES!
console.log(5 === '5');  // false (verschiedene Typen)

// Nicht gleich (loose)
console.log(5 != '5');   // false

// Nicht gleich (strict) - NUTZE DIES!
console.log(5 !== '5');  // true

// Größer
console.log(a > b);      // true

// Kleiner
console.log(a < b);      // false

// Größer oder gleich
console.log(a >= 10);    // true

// Kleiner oder gleich
console.log(b <= 5);     // true

Wichtig: Nutze === und !== statt == und !=!

📝 Quiz

Was gibt 5 > 3 && 2 < 1 zurück?

Logical Operators - Logische Verknüpfungen

&& - UND (AND)

Beide Bedingungen müssen wahr sein:

&& Operator
const alter = 25;
const hatFuehrerschein = true;

// Beide true?
if (alter >= 18 && hatFuehrerschein) {
    console.log('Darf Auto fahren');  // Wird ausgegeben
}

// Wahrheitstabelle
console.log(true && true);    // true
console.log(true && false);   // false
console.log(false && true);   // false
console.log(false && false);  // false

|| - ODER (OR)

Mindestens eine Bedingung muss wahr sein:

|| Operator
const istWochenende = true;
const istFeiertag = false;

// Eine von beiden true?
if (istWochenende || istFeiertag) {
    console.log('Frei!');  // Wird ausgegeben
}

// Wahrheitstabelle
console.log(true || true);    // true
console.log(true || false);   // true
console.log(false || true);   // true
console.log(false || false);  // false

// Fallback-Wert
const userName = null;
const display = userName || 'Gast';
console.log(display);  // 'Gast'

! - NICHT (NOT)

Kehrt Boolean um:

! Operator
const istAngemeldet = false;

// Umkehren
if (!istAngemeldet) {
    console.log('Bitte anmelden');  // Wird ausgegeben
}

// Wahrheitstabelle
console.log(!true);   // false
console.log(!false);  // true

// Double NOT (zu Boolean konvertieren)
console.log(!!'text');  // true
console.log(!!0);       // false

📝 Quiz

Was macht der || (OR) Operator?

Ternary Operator - Kurzform von if/else

Syntax: bedingung ? wennWahr : wennFalsch

Ternary Operator
const alter = 20;

// Normale if/else
let status;
if (alter >= 18) {
    status = 'Erwachsen';
} else {
    status = 'Minderjährig';
}

// Ternary (Kurzform)
const status2 = alter >= 18 ? 'Erwachsen' : 'Minderjährig';
console.log(status2);  // 'Erwachsen'

// Praktisch für Inline
console.log(`Du bist ${alter >= 18 ? 'volljährig' : 'minderjährig'}`);

// Verschachtelt (vermeiden wenn möglich)
const note = 85;
const bewertung = note >= 90 ? 'Sehr gut' :
                  note >= 80 ? 'Gut' :
                  note >= 70 ? 'Befriedigend' :
                  'Nicht bestanden';

📝 Quiz

Was ist das Ergebnis? const x = 10 > 5 ? 'Ja' : 'Nein';

Nullish Coalescing - ?? (ES2020)

Nur bei null oder undefined Fallback:

?? Operator
// Unterschied zu ||
const value1 = 0;
console.log(value1 || 10);  // 10 (0 ist falsy)
console.log(value1 ?? 10);  // 0 (0 ist nicht null/undefined)

const value2 = '';
console.log(value2 || 'Fallback');  // 'Fallback'
console.log(value2 ?? 'Fallback');  // ''

const value3 = null;
console.log(value3 ?? 'Fallback');  // 'Fallback'

// Nützlich für Options
const userCount = 0;
const display = userCount ?? 'Keine Daten';
console.log(display);  // 0 (nicht 'Keine Daten'!)

📝 Quiz

Was ist der Unterschied zwischen || und ???

Optional Chaining - ?. (ES2020)

Sicherer Zugriff auf Properties:

?. Operator
const user = {
    name: 'Max',
    address: {
        city: 'Berlin'
    }
};

// Ohne Optional Chaining
console.log(user.address.city);  // Berlin
// console.log(user.contact.email);  // ❌ TypeError!

// Mit Optional Chaining
console.log(user.address?.city);     // Berlin
console.log(user.contact?.email);    // undefined (kein Fehler!)

// Mit Arrays
const users = [{ name: 'Max' }];
console.log(users[0]?.name);   // Max
console.log(users[5]?.name);   // undefined

// Mit Funktionen
const obj = {
    greet: function() {
        return 'Hallo';
    }
};
console.log(obj.greet?.());   // 'Hallo'
console.log(obj.farewell?.());  // undefined

typeof - Type prüfen

typeof Operator
console.log(typeof 'text');        // 'string'
console.log(typeof 42);            // 'number'
console.log(typeof true);          // 'boolean'
console.log(typeof undefined);     // 'undefined'
console.log(typeof null);          // 'object' (Bug!)
console.log(typeof {});            // 'object'
console.log(typeof []);            // 'object'
console.log(typeof function(){}); // 'function'

// In Bedingungen
const value = 'text';
if (typeof value === 'string') {
    console.log('Es ist ein String');
}

📝 Quiz

Was gibt typeof null zurück?

String Concatenation mit +

String + Operator
// String + String
const vorname = 'Max';
const nachname = 'Mustermann';
console.log(vorname + ' ' + nachname);  // 'Max Mustermann'

// String + Number (wird zu String!)
console.log('Alter: ' + 25);  // 'Alter: 25'
console.log('5' + 3);  // '53' (nicht 8!)

// Vorsicht mit Type Coercion
console.log(2 + 2);      // 4
console.log(2 + '2');    // '22'
console.log('2' + 2);    // '22'
console.log('2' + '2');  // '22'

// Besser: Template Literals
const alter = 25;
console.log(`Alter: ${alter}`);  // 'Alter: 25'

Operator Precedence - Priorität

Welcher Operator wird zuerst ausgeführt?

Operator-Reihenfolge
// Punkt vor Strich
console.log(2 + 3 * 4);  // 14 (nicht 20!)
// = 2 + 12
// = 14

// Klammern haben Priorität
console.log((2 + 3) * 4);  // 20
// = 5 * 4
// = 20

// Komplex
const result = 10 + 5 * 2 - 3;
// = 10 + 10 - 3
// = 17

// Vergleiche vor logischen Operatoren
const a = 5;
const b = 10;
console.log(a < 10 && b > 5);  // true
// = true && true
// = true

Priorität (hoch → niedrig):

  1. () Klammern
  2. ** Potenz
  3. * / % Multiplikation, Division, Modulo
  4. + - Addition, Subtraktion
  5. < > <= >= Vergleiche
  6. === !== Gleichheit
  7. && Logisches UND
  8. || Logisches ODER
  9. ? : Ternary
  10. = Zuweisung

Praktische Beispiele

Beispiel 1: Gerade/Ungerade prüfen

Even/Odd Check
function istGerade(zahl) {
    return zahl % 2 === 0;
}

console.log(istGerade(4));   // true
console.log(istGerade(7));   // false

// Inline mit Ternary
const zahl = 7;
console.log(zahl % 2 === 0 ? 'Gerade' : 'Ungerade');  // 'Ungerade'

Beispiel 2: Rabatt-Rechner

Discount Calculator
const preis = 100;
const rabatt = 20;  // 20%

// Rabatt berechnen
const rabattBetrag = preis * (rabatt / 100);
console.log('Rabatt:', rabattBetrag);  // 20

// Endpreis
const endpreis = preis - rabattBetrag;
console.log('Endpreis:', endpreis);  // 80

// Kurzform
const endpreis2 = preis * (1 - rabatt / 100);
console.log(endpreis2);  // 80

Beispiel 3: Form Validation

Input Validation
const username = 'max';
const password = '12345';

// Validierung
const isUsernameValid = username.length >= 3;
const isPasswordValid = password.length >= 6;

if (isUsernameValid && isPasswordValid) {
    console.log('Anmeldung erfolgreich');
} else {
    if (!isUsernameValid) {
        console.log('Username zu kurz (min. 3 Zeichen)');
    }
    if (!isPasswordValid) {
        console.log('Passwort zu kurz (min. 6 Zeichen)');
    }
}

Beispiel 4: Temperature Converter

Celsius to Fahrenheit
const celsius = 25;

// Formel: F = C * 9/5 + 32
const fahrenheit = celsius * 9 / 5 + 32;
console.log(`${celsius}°C = ${fahrenheit}°F`);  // 25°C = 77°F

// Mit Runden
const fahrenheit2 = Math.round(celsius * 9 / 5 + 32);
console.log(fahrenheit2);  // 77

Best Practices

✅ DO:

  1. === statt == (strict equality)
  2. !== statt !=
  3. Klammern für Klarheit
  4. Template Literals statt + für Strings
  5. Ternary für einfache if/else
  6. ?? für null/undefined Fallbacks

❌ DON'T:

  1. Nicht == oder != (Type Coercion!)
  2. Nicht ++ in Expressions (verwirrend)
  3. Nicht zu viele verschachtelte Ternary
  4. Nicht komplexe Logik in einer Zeile
  5. Nicht || für 0 oder '' Fallbacks (nutze ??)

📝 Quiz

Was ist der Unterschied zwischen == und ===?

TipsAndTricks

Tipps & Tricks

=== statt == immer nutzen

Vermeide Type Coercion Probleme:

// ❌ == konvertiert Typen
console.log(5 == '5');      // true (überraschend!)
console.log(0 == false);    // true
console.log('' == false);   // true

// ✅ === prüft Wert UND Typ
console.log(5 === '5');     // false (wie erwartet)
console.log(0 === false);   // false
console.log('' === false);  // false

// Best Practice: Immer === und !== nutzen!

Nullish Coalescing für 0 und ''

Nutze ?? statt || für Fallback-Werte:

// Problem mit ||
const count = 0;
const display = count || 'Keine Daten';  // 'Keine Daten' ❌

// Lösung mit ??
const display = count ?? 'Keine Daten';  // 0 ✅

// Praktisch für Config
const port = config.port ?? 3000;
const debug = config.debug ?? false;

Optional Chaining für sichere Zugriffe

Vermeide TypeError bei undefined/null:

const user = { address: { city: 'Berlin' } };

// ❌ Fehleranfällig
const phone = user.contact.phone;  // TypeError!

// ✅ Mit Optional Chaining
const phone = user?.contact?.phone;  // undefined (kein Fehler)

// Auch bei Arrays und Functions
const firstUser = users?.[0];
const greeting = user?.greet?.();

Ternary für kurze if/else

Spare Zeilen bei einfachen Bedingungen:

// ❌ Verbose
let status;
if (age >= 18) {
    status = 'Erwachsen';
} else {
    status = 'Minderjährig';
}

// ✅ Ternary (eine Zeile)
const status = age >= 18 ? 'Erwachsen' : 'Minderjährig';

// In Template Strings
console.log(`Du bist ${age >= 18 ? 'volljährig' : 'minderjährig'}`);

📝 Quiz

Was gibt 10 % 3 zurück?

Übungsaufgaben

Aufgabe 1: Rechner

Erstelle Variables:

  • Zwei Zahlen
  • Berechne +, -, *, /, %
  • Gebe Ergebnisse aus

Aufgabe 2: Vergleiche

Prüfe mit ===:

  • Zwei Numbers gleich?
  • String und Number gleich?
  • Boolean und Number gleich?

Aufgabe 3: Gerade/Ungerade

Schreibe Code der prüft:

  • Ist Zahl gerade? (% 2 === 0)
  • Nutze if/else oder Ternary
  • Teste mit verschiedenen Zahlen

Nächste Schritte

Du kennst jetzt:

  • ✅ Arithmetic Operators (+, -, *, /, %, **)
  • ✅ Assignment Operators (+=, -=, etc.)
  • ✅ Comparison Operators (===, !==, <, >)
  • ✅ Logical Operators (&&, ||, !)
  • ✅ Ternary Operator (? :)
  • ✅ Nullish Coalescing (??)
  • ✅ Optional Chaining (?.)
  • ✅ Operator Precedence

Als Nächstes lernst du:

  • Conditionals (if, else, else if, switch)
  • Loops (for, while, do-while)
  • Functions

Weiter so! 🚀

JavaScriptLektion 5 von 17
29% abgeschlossen
Lektion abgeschlossen!

Gut gemacht! 🎉

Du hast "JavaScript Operators - Arithmetik, Vergleiche & Logik" abgeschlossen

Artikel bewerten

0.0 (0 Bewertungen)

Bitte einloggen um zu bewerten