Anfänger132025-01-15

JavaScript Conditionals - if, else, switch

Lerne JavaScript Conditionals: if, else, else if, switch - Vergleiche, Logische Operatoren, Truthy/Falsy und Best Practices für Bedingungen.

#javascript#conditionals#if#else#switch#comparison

JavaScript Conditionals

Conditionals (Bedingungen) erlauben deinem Code Entscheidungen zu treffen. Basierend auf Bedingungen wird unterschiedlicher Code ausgeführt.

Was sind Conditionals?

Conditionals führen Code nur aus, wenn eine Bedingung erfüllt ist:

Conditional Konzept
// Wenn Bedingung wahr ist, tu etwas
if (alter >= 18) {
    console.log('Du bist volljährig');
}

Im echten Leben:

  • Wenn es regnet, dann nimm einen Regenschirm
  • Wenn du Hunger hast, dann iss etwas
  • Wenn Ampel grün, dann fahre los

if - Einfache Bedingung

Syntax:

if Statement
if (bedingung) {
    // Code wird ausgeführt wenn bedingung true ist
}

Beispiele:

if Beispiele
const alter = 20;

if (alter >= 18) {
    console.log('Volljährig');
}

const temperatur = 25;

if (temperatur > 30) {
    console.log('Es ist heiß!');
}

const istEingeloggt = true;

if (istEingeloggt) {
    console.log('Willkommen zurück!');
}

// Mit Vergleich
const name = 'Max';

if (name === 'Max') {
    console.log('Hallo Max!');
}

else - Alternative

Wenn Bedingung nicht erfüllt:

if...else
if (bedingung) {
    // Code wenn true
} else {
    // Code wenn false
}

Beispiele:

if...else Beispiele
const alter = 16;

if (alter >= 18) {
    console.log('Du bist volljährig');
} else {
    console.log('Du bist minderjährig');
}

const temperatur = 15;

if (temperatur > 20) {
    console.log('T-Shirt anziehen');
} else {
    console.log('Jacke anziehen');
}

const istWochenende = false;

if (istWochenende) {
    console.log('Ausschlafen!');
} else {
    console.log('Wecker stellen!');
}

else if - Mehrere Bedingungen

Mehrere Alternativen prüfen:

if...else if...else
if (bedingung1) {
    // Code wenn bedingung1 true
} else if (bedingung2) {
    // Code wenn bedingung2 true
} else {
    // Code wenn alle false
}

Beispiele:

else if Beispiele
const note = 85;

if (note >= 90) {
    console.log('Sehr gut!');
} else if (note >= 75) {
    console.log('Gut!');
} else if (note >= 60) {
    console.log('Befriedigend');
} else if (note >= 50) {
    console.log('Ausreichend');
} else {
    console.log('Durchgefallen');
}

const uhrzeit = 14;

if (uhrzeit < 12) {
    console.log('Guten Morgen!');
} else if (uhrzeit < 18) {
    console.log('Guten Tag!');
} else {
    console.log('Guten Abend!');
}

const alter = 25;

if (alter < 13) {
    console.log('Kind');
} else if (alter < 18) {
    console.log('Jugendlicher');
} else if (alter < 65) {
    console.log('Erwachsener');
} else {
    console.log('Senior');
}

Vergleichsoperatoren in Conditionals

Alle Vergleiche:

Vergleichsoperatoren
const x = 10;

// Gleichheit (strict)
if (x === 10) {
    console.log('x ist 10');
}

// Ungleichheit
if (x !== 5) {
    console.log('x ist nicht 5');
}

// Größer als
if (x > 5) {
    console.log('x größer als 5');
}

// Kleiner als
if (x < 20) {
    console.log('x kleiner als 20');
}

// Größer gleich
if (x >= 10) {
    console.log('x größer oder gleich 10');
}

// Kleiner gleich
if (x <= 10) {
    console.log('x kleiner oder gleich 10');
}

Wichtig: Immer === statt == nutzen!

=== vs ==
// ❌ SCHLECHT: == konvertiert Typen
if (5 == '5') {
    console.log('true');  // true (verwirrend!)
}

// ✅ GUT: === vergleicht Wert UND Typ
if (5 === '5') {
    console.log('true');  // false
}

if (5 === 5) {
    console.log('true');  // true
}

Logische Operatoren

&& (UND) - Beide Bedingungen müssen wahr sein

&& (AND)
const alter = 25;
const hatFuehrerschein = true;

// Beide Bedingungen müssen true sein
if (alter >= 18 && hatFuehrerschein) {
    console.log('Darf Auto fahren');
}

const temperatur = 25;
const istSonnig = true;

if (temperatur > 20 && istSonnig) {
    console.log('Perfektes Wetter!');
}

// Mehrere Bedingungen
const x = 15;

if (x > 10 && x < 20 && x !== 15) {
    console.log('x ist zwischen 10 und 20, aber nicht 15');
}

|| (ODER) - Mindestens eine Bedingung muss wahr sein

|| (OR)
const tag = 'Samstag';

// Eine Bedingung muss true sein
if (tag === 'Samstag' || tag === 'Sonntag') {
    console.log('Wochenende!');
}

const alter = 16;

if (alter < 13 || alter > 65) {
    console.log('Ermäßigter Eintritt');
}

const rolle = 'admin';

if (rolle === 'admin' || rolle === 'moderator') {
    console.log('Zugriff erlaubt');
}

! (NICHT) - Negiert die Bedingung

! (NOT)
const istEingeloggt = false;

// Negiert den Wert
if (!istEingeloggt) {
    console.log('Bitte einloggen');
}

const hatZugriff = true;

if (!hatZugriff) {
    console.log('Kein Zugriff');
} else {
    console.log('Zugriff erlaubt');
}

// Mit Vergleich
const alter = 16;

if (!(alter >= 18)) {
    console.log('Zu jung');
}

Kombinierte Logische Operatoren

Kombinationen
const alter = 25;
const istStudent = true;
const hatGutschein = false;

// && und ||
if ((alter < 18 || istStudent) && !hatGutschein) {
    console.log('Studentenrabatt möglich');
}

const temperatur = 28;
const istWochenende = true;
const istRegen = false;

if (temperatur > 25 && istWochenende && !istRegen) {
    console.log('Perfekt für den Strand!');
}

// Gruppierung mit Klammern
const x = 10;

if ((x > 5 && x < 15) || x === 20) {
    console.log('Bedingung erfüllt');
}

Truthy und Falsy Values

JavaScript konvertiert Werte zu Boolean:

Truthy/Falsy in Conditionals
// Falsy Values (werden zu false)
if (false) { }        // false
if (0) { }            // false
if ('') { }           // false (leerer String)
if (null) { }         // false
if (undefined) { }    // false
if (NaN) { }          // false

// Alles andere ist Truthy (wird zu true)
if (true) { }         // true
if (1) { }            // true
if ('text') { }       // true
if ([]) { }           // true (leeres Array!)
if ({}) { }           // true (leeres Object!)

// Praktische Beispiele
let userName = '';

if (userName) {
    console.log(`Hallo ${userName}`);
} else {
    console.log('Bitte Namen eingeben');
}

let count = 0;

if (count) {
    console.log('Count ist ' + count);
} else {
    console.log('Count ist 0');
}

// Prüfen ob Variable existiert
let user;

if (user) {
    console.log('User existiert');
} else {
    console.log('User nicht definiert');
}

Verschachtelte Conditionals

Conditionals in Conditionals:

Nested if
const alter = 25;
const hatTicket = true;
const hatAusweis = true;

if (alter >= 18) {
    console.log('Volljährig');

    if (hatTicket) {
        console.log('Ticket vorhanden');

        if (hatAusweis) {
            console.log('Einlass erlaubt!');
        } else {
            console.log('Bitte Ausweis zeigen');
        }
    } else {
        console.log('Bitte Ticket kaufen');
    }
} else {
    console.log('Zu jung für diese Veranstaltung');
}

// Besser: Mit && kombinieren
if (alter >= 18 && hatTicket && hatAusweis) {
    console.log('Einlass erlaubt!');
} else {
    console.log('Einlass verweigert');
}

Tipp: Vermeide zu tiefe Verschachtelung (max 2-3 Ebenen)!

switch - Mehrere feste Werte

Alternative zu vielen else if:

switch Statement
switch (ausdruck) {
    case wert1:
        // Code
        break;
    case wert2:
        // Code
        break;
    default:
        // Code wenn kein case passt
}

Beispiele:

switch Beispiele
const tag = 'Montag';

switch (tag) {
    case 'Montag':
        console.log('Wochenstart!');
        break;
    case 'Freitag':
        console.log('Fast Wochenende!');
        break;
    case 'Samstag':
    case 'Sonntag':
        console.log('Wochenende!');
        break;
    default:
        console.log('Normaler Werktag');
}

const note = 1;

switch (note) {
    case 1:
        console.log('Sehr gut!');
        break;
    case 2:
        console.log('Gut!');
        break;
    case 3:
        console.log('Befriedigend');
        break;
    case 4:
        console.log('Ausreichend');
        break;
    case 5:
    case 6:
        console.log('Durchgefallen');
        break;
    default:
        console.log('Ungültige Note');
}

const farbe = 'rot';

switch (farbe) {
    case 'rot':
        console.log('Stopp!');
        break;
    case 'gelb':
        console.log('Achtung!');
        break;
    case 'grün':
        console.log('Los!');
        break;
    default:
        console.log('Unbekannte Farbe');
}

Wichtig: break verhindert Fall-through!

Fall-through ohne break
const monat = 2;

switch (monat) {
    case 1:
        console.log('Januar');
        // Kein break!
    case 2:
        console.log('Februar');
        // Kein break!
    case 3:
        console.log('März');
        break;
}

// Ausgabe:
// Februar
// März

// Mit break (korrekt)
switch (monat) {
    case 1:
        console.log('Januar');
        break;
    case 2:
        console.log('Februar');
        break;
    case 3:
        console.log('März');
        break;
}

if vs. switch

Wann was nutzen?

if vs. switch
// ✅ if für Bereiche
const alter = 25;

if (alter < 18) {
    console.log('Minderjährig');
} else if (alter < 65) {
    console.log('Erwachsen');
} else {
    console.log('Senior');
}

// ✅ switch für feste Werte
const rolle = 'admin';

switch (rolle) {
    case 'admin':
        console.log('Vollzugriff');
        break;
    case 'moderator':
        console.log('Teilzugriff');
        break;
    case 'user':
        console.log('Lesezugriff');
        break;
}

// ❌ SCHLECHT: switch für Bereiche
switch (true) {
    case alter < 18:
        console.log('Minderjährig');
        break;
    // Funktioniert, ist aber verwirrend!
}

Faustregel:

  • if: Bereiche, komplexe Bedingungen, wenige Optionen
  • switch: Viele feste Werte, einfache Gleichheit

Ternary Operator (Kurzform)

Einzeilige if-else Alternative:

Ternary Operator
// Syntax: bedingung ? wennTrue : wennFalse

const alter = 20;
const status = alter >= 18 ? 'Volljährig' : 'Minderjährig';
console.log(status);  // Volljährig

// Statt:
let status2;
if (alter >= 18) {
    status2 = 'Volljährig';
} else {
    status2 = 'Minderjährig';
}

// Weitere Beispiele
const punkte = 85;
const note = punkte >= 50 ? 'Bestanden' : 'Durchgefallen';

const istOnline = true;
console.log(istOnline ? '🟢 Online' : '🔴 Offline');

// In Template String
const name = 'Max';
console.log(`Hallo ${name === 'Max' ? 'Chef' : 'Besucher'}`);

// Verschachtelt (vermeiden!)
const x = 10;
const result = x > 10 ? 'groß' : x < 10 ? 'klein' : 'genau 10';

Nur für einfache Bedingungen nutzen!

Praktische Beispiele

Beispiel 1: Altersvalidierung

Alter prüfen
const alter = 16;

if (alter < 0) {
    console.log('❌ Ungültiges Alter');
} else if (alter < 13) {
    console.log('Kind: Begleitung erforderlich');
} else if (alter < 18) {
    console.log('Jugendlicher: Eingeschränkter Zugang');
} else if (alter < 100) {
    console.log('✅ Vollzugriff');
} else {
    console.log('❌ Ungültiges Alter');
}

Beispiel 2: Login-Check

Login Validation
const username = 'admin';
const password = '12345';

if (!username || !password) {
    console.log('❌ Bitte alle Felder ausfüllen');
} else if (username === 'admin' && password === '12345') {
    console.log('✅ Login erfolgreich');
} else {
    console.log('❌ Falscher Username oder Passwort');
}

Beispiel 3: Rabatt-Rechner

Discount Calculator
const preis = 100;
const istStudent = true;
const hatGutschein = true;

let rabatt = 0;

if (istStudent) {
    rabatt += 10;  // 10% Studentenrabatt
}

if (hatGutschein) {
    rabatt += 5;   // 5% Gutschein
}

if (preis > 50) {
    rabatt += 5;   // 5% ab 50€
}

const endpreis = preis - (preis * rabatt / 100);
console.log(`Rabatt: ${rabatt}%`);
console.log(`Endpreis: ${endpreis}€`);

Beispiel 4: Notenrechner

Grade Calculator
const punkte = 85;
let note;
let text;

if (punkte >= 90) {
    note = 1;
    text = 'Sehr gut!';
} else if (punkte >= 80) {
    note = 2;
    text = 'Gut!';
} else if (punkte >= 70) {
    note = 3;
    text = 'Befriedigend';
} else if (punkte >= 60) {
    note = 4;
    text = 'Ausreichend';
} else if (punkte >= 50) {
    note = 5;
    text = 'Mangelhaft';
} else {
    note = 6;
    text = 'Ungenügend';
}

console.log(`Note: ${note} - ${text}`);
console.log(punkte >= 50 ? '✅ Bestanden' : '❌ Durchgefallen');

Beispiel 5: Wetter-App

Weather Advice
const temperatur = 22;
const istRegen = false;
const istWindig = true;

if (istRegen) {
    console.log('☔ Regenschirm mitnehmen!');
} else if (temperatur < 10) {
    console.log('🧥 Warme Jacke anziehen!');
} else if (temperatur > 25) {
    console.log('👕 T-Shirt reicht!');
} else {
    console.log('👔 Leichte Jacke empfohlen');
}

if (istWindig && !istRegen) {
    console.log('🌬️ Windjacke mitnehmen');
}

if (temperatur > 20 && !istRegen) {
    console.log('😎 Perfektes Wetter für draußen!');
}

Best Practices

✅ DO:

  1. === statt == (strict equality)
  2. Klammern bei && und || für Klarheit
  3. Früh returnen (Guard Clauses)
  4. Positive Bedingungen bevorzugen
  5. Default-Cases bei switch
Good Practices
// ✅ Guard Clause (früh return)
function checkAge(age) {
    if (age < 0) {
        return 'Ungültig';
    }

    if (age < 18) {
        return 'Minderjährig';
    }

    return 'Volljährig';
}

// ✅ Positive Bedingungen
if (istAktiv) {
    // ...
} else {
    // ...
}

// ✅ Klammern für Klarheit
if ((x > 5 && x < 10) || (y > 20 && y < 30)) {
    // ...
}

❌ DON'T:

  1. Nicht zu tief verschachteln
  2. Nicht == nutzen
  3. Nicht ohne break bei switch
  4. Nicht zu komplexe Bedingungen
Anti-Patterns
// ❌ SCHLECHT: Zu tief verschachtelt
if (a) {
    if (b) {
        if (c) {
            if (d) {
                // Zu tief!
            }
        }
    }
}

// ✅ BESSER: Mit &&
if (a && b && c && d) {
    // Viel besser!
}

// ❌ SCHLECHT: == statt ===
if (5 == '5') {
    // Konvertiert Typen!
}

// ✅ BESSER: ===
if (5 === 5) {
    // Vergleicht Wert UND Typ
}

// ❌ SCHLECHT: Fehlende breaks
switch (x) {
    case 1:
        console.log('1');
    case 2:
        console.log('2');  // Wird auch ausgeführt!
}

TipsAndTricks

Tipps & Tricks

Guard Clauses für cleanen Code

Prüfe Fehler-Fälle zuerst und return früh:

// ❌ Verschachtelt
function processOrder(order) {
    if (order) {
        if (order.items.length > 0) {
            if (order.isPaid) {
                // Verarbeite Order
            }
        }
    }
}

// ✅ Mit Guard Clauses
function processOrder(order) {
    if (!order) return;
    if (order.items.length === 0) return;
    if (!order.isPaid) return;
    // Verarbeite Order
}

Ternary für einfache if/else

Spare Zeilen mit dem Ternary Operator:

// Standard if/else
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'}`);

Nullish Coalescing statt ||

Nutze ?? für null/undefined Checks:

// Problem mit ||
const count = 0;
const display = count || 'Keine Daten';  // 'Keine Daten' (falsch!)

// Lösung mit ??
const display = count ?? 'Keine Daten';  // 0 (richtig!)

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

Switch mit Fall-Through clever nutzen

Gruppiere mehrere Cases für gleiche Aktionen:

switch (day) {
    case 'Montag':
    case 'Dienstag':
    case 'Mittwoch':
    case 'Donnerstag':
    case 'Freitag':
        console.log('Wochentag - Arbeiten!');
        break;
    case 'Samstag':
    case 'Sonntag':
        console.log('Wochenende - Frei!');
        break;
}

📝 Quiz

Was ist der Unterschied zwischen if...else if und mehreren if?

📝 Quiz

Wann sollte man switch statt if nutzen?

Übungsaufgaben

Aufgabe 1: Altersprüfung

Erstelle ein Programm das:

  • Alter-Variable hat
  • Prüft ob < 13, < 18, < 65, oder darüber
  • Entsprechende Kategorie ausgibt

Aufgabe 2: Tageszeit-Gruß

Erstelle eine Variable stunde:

  • 0-11: "Guten Morgen"
  • 12-17: "Guten Tag"
  • 18-21: "Guten Abend"
  • 22-23: "Gute Nacht"

Aufgabe 3: Wochentag-Check

Mit switch:

  • Variable für Wochentag (1-7)
  • Gebe den Namen aus (Montag - Sonntag)
  • Prüfe ob Wochenende (Samstag/Sonntag)

Aufgabe 4: Login-System

Erstelle:

  • username und password Variables
  • Prüfe beide Felder ausgefüllt
  • Prüfe Credentials korrekt
  • Gebe entsprechende Meldung aus

Nächste Schritte

Du kennst jetzt:

  • ✅ if, else, else if
  • ✅ switch Statements
  • ✅ Vergleichsoperatoren (===, !==, <, >)
  • ✅ Logische Operatoren (&&, ||, !)
  • ✅ Truthy & Falsy Values
  • ✅ Verschachtelte Conditionals
  • ✅ Ternary Operator
  • ✅ Best Practices

Als Nächstes lernst du:

  • Loops (for, while, forEach)
  • Iteration über Arrays
  • Do-while Loops
  • Break & Continue

Weiter so! 🚀

JavaScriptLektion 6 von 17
35% abgeschlossen
Lektion abgeschlossen!

Gut gemacht! 🎉

Du hast "JavaScript Conditionals - if, else, switch" abgeschlossen

Artikel bewerten

0.0 (0 Bewertungen)

Bitte einloggen um zu bewerten