JavaScript Anfänger

JavaScript Operatoren verstehen

JavaScript Operatoren

Operatoren sind Symbole, die Operationen auf Werten ausführen. Sie sind die Grundbausteine für Berechnungen, Vergleiche und Logik in deinem Code.

Arithmetische Operatoren

Für mathematische Berechnungen:

const a = 10;
const b = 3;

// Grundrechenarten
console.log(a + b);   // 13 (Addition)
console.log(a - b);   // 7  (Subtraktion)
console.log(a * b);   // 30 (Multiplikation)
console.log(a / b);   // 3.333... (Division)
console.log(a % b);   // 1  (Modulo/Rest)
console.log(a ** b);  // 1000 (Potenz: 10³)

Modulo-Operator %

Gibt den Rest einer Division zurück:

console.log(10 % 3);  // 1 (10 ÷ 3 = 3 Rest 1)
console.log(8 % 2);   // 0 (8 ÷ 2 = 4 Rest 0)
console.log(7 % 4);   // 3 (7 ÷ 4 = 1 Rest 3)

// Praktischer Einsatz: Gerade/Ungerade prüfen
const zahl = 7;
if (zahl % 2 === 0) {
    console.log("Gerade");
} else {
    console.log("Ungerade");
}

// Zyklische Wiederholung (z.B. für Animationen)
const index = 5;
const arrayLength = 3;
console.log(index % arrayLength); // 2 (bleibt immer im Bereich 0-2)

Inkrement & Dekrement

let count = 5;

count++;        // count = count + 1 → 6
count--;        // count = count - 1 → 5

// Prefix vs Postfix
let x = 5;
console.log(x++); // 5 (gibt erst aus, dann erhöht)
console.log(x);   // 6

let y = 5;
console.log(++y); // 6 (erhöht erst, dann ausgibt)
console.log(y);   // 6

Zuweisungsoperatoren

Kurzschreibweisen für Berechnungen mit Zuweisung:

let x = 10;

x += 5;   // x = x + 5   → 15
x -= 3;   // x = x - 3   → 12
x *= 2;   // x = x * 2   → 24
x /= 4;   // x = x / 4   → 6
x %= 4;   // x = x % 4   → 2
x **= 3;  // x = x ** 3  → 8

// Für Strings
let text = "Hallo";
text += " Welt";  // "Hallo Welt"

Vergleichsoperatoren

Vergleichen Werte und geben true oder false zurück:

const a = 5;
const b = 10;
const c = "5";

// Größer/Kleiner
console.log(a > b);   // false
console.log(a < b);   // true
console.log(a >= 5);  // true
console.log(b <= 10); // true

// Gleichheit
console.log(a == c);  // true ⚠️ (nur Wert, ignoriert Typ)
console.log(a === c); // false ✅ (Wert UND Typ)

// Ungleichheit
console.log(a != c);  // false ⚠️
console.log(a !== c); // true ✅

== vs === (Wichtig!)

// == führt Type Coercion durch
console.log(5 == "5");      // true 🤔
console.log(0 == false);    // true 🤔
console.log(null == undefined); // true 🤔
console.log("" == 0);       // true 🤔

// === prüft Wert UND Typ (IMMER NUTZEN!)
console.log(5 === "5");     // false ✅
console.log(0 === false);   // false ✅
console.log(null === undefined); // false ✅

Regel: Verwende IMMER === und !==!

Logische Operatoren

Kombinieren Boolesche Ausdrücke:

UND &&

Beide Seiten müssen true sein:

const age = 25;
const hasLicense = true;

// Beide Bedingungen müssen erfüllt sein
if (age >= 18 && hasLicense) {
    console.log("Darf Auto fahren");
}

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

ODER ||

Mindestens eine Seite muss true sein:

const isWeekend = true;
const isHoliday = false;

if (isWeekend || isHoliday) {
    console.log("Frei! 🎉");
}

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

NICHT !

Kehrt den Wert um:

const isLoggedIn = false;

if (!isLoggedIn) {
    console.log("Bitte einloggen");
}

console.log(!true);  // false
console.log(!false); // true
console.log(!!0);    // false (doppelte Negation → Boolean-Konvertierung)
console.log(!!"");   // false
console.log(!!"hi"); // true

Nullish Coalescing ??

Gibt den rechten Wert zurück, wenn der linke null oder undefined ist:

const username = null;
const displayName = username ?? "Gast";
console.log(displayName); // "Gast"

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

const text = "";
console.log(text || "default");  // "default" ("" ist falsy!)
console.log(text ?? "default");  // "" ("" ist nicht null/undefined)

Optional Chaining ?.

Sicherer Zugriff auf verschachtelte Eigenschaften:

const user = {
    name: "Max",
    address: {
        city: "Berlin"
    }
};

// Ohne Optional Chaining
// console.log(user.settings.theme); // ❌ Error!

// Mit Optional Chaining
console.log(user.settings?.theme);   // undefined (kein Error!)
console.log(user.address?.city);     // "Berlin"
console.log(user.address?.zip);      // undefined

// Auch für Methoden
const obj = {};
obj.someMethod?.(); // Ruft nur auf, wenn existiert

Ternärer Operator ? :

Kurzschreibweise für if/else:

// Syntax: bedingung ? wertWennTrue : wertWennFalse

const age = 20;
const status = age >= 18 ? "Erwachsen" : "Minderjährig";
console.log(status); // "Erwachsen"

// Statt:
let status2;
if (age >= 18) {
    status2 = "Erwachsen";
} else {
    status2 = "Minderjährig";
}

// Praktische Anwendungen
const score = 85;
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";

// Für Anzeige
const count = 5;
const text = `${count} ${count === 1 ? "Item" : "Items"}`;
// "5 Items"

String-Operatoren

// Konkatenation mit +
const firstName = "Max";
const lastName = "Mustermann";
const fullName = firstName + " " + lastName;
console.log(fullName); // "Max Mustermann"

// Template Literals (besser!)
const greeting = `Hallo, ${firstName} ${lastName}!`;
console.log(greeting); // "Hallo, Max Mustermann!"

// += für Strings
let message = "Hallo";
message += " Welt";
console.log(message); // "Hallo Welt"

Spread-Operator ...

Verteilt Elemente aus Arrays oder Objekten:

// Arrays zusammenführen
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// Array kopieren
const original = [1, 2, 3];
const copy = [...original];

// Elemente hinzufügen
const withMore = [0, ...arr1, 4];
console.log(withMore); // [0, 1, 2, 3, 4]

// Objekte zusammenführen
const defaults = { theme: "light", lang: "de" };
const userPrefs = { theme: "dark" };
const settings = { ...defaults, ...userPrefs };
console.log(settings); // { theme: "dark", lang: "de" }

// Funktion mit beliebig vielen Argumenten
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10

Operator-Priorität

JavaScript führt Operatoren in einer bestimmten Reihenfolge aus:

// Höchste Priorität zuerst
console.log(2 + 3 * 4);     // 14 (nicht 20!)
console.log((2 + 3) * 4);   // 20 (Klammern zuerst)

// Priorität (von hoch nach niedrig):
// 1. () Klammern
// 2. ** Potenz
// 3. *, /, % Multiplikation, Division, Modulo
// 4. +, - Addition, Subtraktion
// 5. <, >, <=, >= Vergleiche
// 6. ==, ===, !=, !== Gleichheit
// 7. && UND
// 8. || ODER
// 9. ?? Nullish Coalescing
// 10. ? : Ternär
// 11. = Zuweisung

// Beispiel
const result = 2 + 3 * 4 > 10 && true || false;
// Schritt 1: 3 * 4 = 12
// Schritt 2: 2 + 12 = 14
// Schritt 3: 14 > 10 = true
// Schritt 4: true && true = true
// Schritt 5: true || false = true
console.log(result); // true

// Bei Unsicherheit: Klammern nutzen!
const clear = ((2 + (3 * 4)) > 10) && true;

Praktische Beispiele

Preisberechnung

const price = 49.99;
const quantity = 3;
const discount = 0.1; // 10%

const subtotal = price * quantity;
const discountAmount = subtotal * discount;
const total = subtotal - discountAmount;

console.log(`Zwischensumme: ${subtotal.toFixed(2)} €`);
console.log(`Rabatt: -${discountAmount.toFixed(2)} €`);
console.log(`Gesamt: ${total.toFixed(2)} €`);

Formular-Validierung

const username = "max";
const password = "123456";
const confirmPassword = "123456";

const isUsernameValid = username.length >= 3 && username.length <= 20;
const isPasswordValid = password.length >= 6;
const doPasswordsMatch = password === confirmPassword;

const isFormValid = isUsernameValid && isPasswordValid && doPasswordsMatch;

if (isFormValid) {
    console.log("Registrierung erfolgreich!");
} else {
    !isUsernameValid && console.log("Username ungültig");
    !isPasswordValid && console.log("Passwort zu kurz");
    !doPasswordsMatch && console.log("Passwörter stimmen nicht überein");
}

Konfiguration mit Fallbacks

const userConfig = {
    theme: null,
    fontSize: 14
};

const config = {
    theme: userConfig.theme ?? "light",
    fontSize: userConfig.fontSize ?? 16,
    language: userConfig.language ?? "de"
};

console.log(config);
// { theme: "light", fontSize: 14, language: "de" }

Zusammenfassung

OperatorBeschreibungBeispiel
+, -, *, /, %Mathematik5 + 3
**Potenz2 ** 3 → 8
++, --Inkrement/Dekrementcount++
+=, -=, *=, /=Zuweisung mit Operationx += 5
===, !==Strikte Gleichheit5 === "5" → false
&&, ||, !Logischtrue && false
??Nullish Coalescingnull ?? "default"
?.Optional Chainingobj?.prop
? :Ternärx ? "ja" : "nein"
...Spread[...arr]

💡 Pro-Tipp: Verwende immer === statt ==. Nutze ?? für Default-Werte und ?. für sicheren Zugriff auf verschachtelte Objekte!