BeginnerLesson 3 of 16
Conditions & Comparisons – JavaScript
if, switch, === instead of ==, truthy/falsy and the operators ?? and ?.
With if you run code only when a condition is true. The block goes in curly braces.
const punkte = 73;
let note;
if (punkte >= 90) {
note = "very good";
} else if (punkte >= 70) {
note = "good";
} else {
note = "needs improvement";
}
console.log(note);
const status = punkte >= 50 ? "passed" : "failed"; // Ternary
console.log(status);Always compare with the strict operator === (and !==). The loose operator == converts types and gives surprising results.
console.log(5 == "5", 5 === "5"); // true false
console.log(null == undefined, null === undefined); // true false
console.log(0 == "", 0 === ""); // true falseIn conditions, six values count as "falsy": false, 0, "", null, undefined and NaN (plus 0n). Everything else is "truthy" – including empty arrays [], objects {} and the string "0".
console.log(Boolean([]), Boolean(""), Boolean("0"), Boolean(0)); // true false true false
const eingabe = 0;
console.log(eingabe || 10); // 10 (|| replaces any falsy value)
console.log(eingabe ?? 10); // 0 (?? replaces only null/undefined)
const user = { profil: { name: "Ada" } };
console.log(user.profil?.name, user.adresse?.stadt); // Ada undefinedFor many fixed cases, switch is clearer. Do not forget break, otherwise execution "falls through" into the next case:
const tag = "sa";
switch (tag) {
case "sa":
case "so":
console.log("Weekend");
break;
default:
console.log("Weekday");
}Tip
?? (nullish coalescing) is almost always better than || for default values, because 0 and "" remain valid inputs. ?. (optional chaining) stops at null/undefined instead of throwing an error.