🔀 Warunki (if/else/unless)

Instrukcje warunkowe pozwalają wykonywać różny kod w zależności od warunków.

if / else

// Podstawowy if if (x > 10) { print("x jest większe od 10"); } // if-else if (x > 10) { print("duże"); } else { print("małe"); } // if-else if-else if (x > 10) { print("big"); } else if (x > 5) { print("medium"); } else { print("small"); }

unless

unless to przeciwieństwo if - wykonuje się gdy warunek jest FAŁSZYWY:

let isAdmin = false; // unless - czytelniejsze niż if (!condition) unless (isAdmin) { print("Brak uprawnień!"); } // unless z else unless (isLoggedIn) { print("Proszę się zalogować"); } else { print("Witaj ponownie!"); } // Równoważne z: if (!isAdmin) { print("Brak uprawnień!"); }

Operator trójargumentowy (ternary)

let result = (x > 0) ? "positive" : "non-positive"; // Zagnieżdżony (używaj ostrożnie) let grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";

Wartości truthy/falsy

// Wartości "falsy" (traktowane jak false): // false, 0, "", null // Wartości "truthy" (wszystko inne): // true, 1, "text", [], {}, itd. if (0) print("nie wykona się"); if (1) print("wykona się"); if ("") print("nie wykona się"); if ("hello") print("wykona się");

Skrócone formy

// Logical AND (&&) jako guard isValid && process(data); // wywołaj tylko gdy isValid // Logical OR (||) jako default let name = userName || "Anonymous"; // Null coalescing (??) - tylko dla null let value = config ?? "default"; // Elvis operator (?:) - dla wszystkich falsy let result = input ?: "default";

Type guards (is)

fn process(value) { if (value is string) { return "String: " + value; } if (value is number) { return "Number: " + (value * 2); } if (value is list) { return "List with " + size(value) + " items"; } return "Unknown"; }
💡 Kiedy używać unless?

Używaj unless gdy sprawdzasz warunek negatywny. unless (isError) jest czytelniejsze niż if (!isError).