~/
hackweb.dev
JavaScript if/else & Truthy/Falsy
Quiz
⌘K
...
~/
/tutorials
/js/js-if-else/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/4js-if-else
Write
Preview
Diff
# JavaScript if/else & Truthy/Falsy Conditionals let your code make decisions based on different situations. ## if Statement Checks a condition and runs code only if it's true: ```javascript let temperature = 30; if (temperature > 25) { console.log("It's hot outside!"); } ``` ## else Statement Provides an alternative when the condition is false: ```javascript let temperature = 15; if (temperature > 25) { console.log("It's hot!"); } else { console.log("It's cool!"); } ``` ## else if — Multiple Conditions ```javascript let score = 85; let grade; if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else { grade = "F"; } ``` JavaScript checks conditions in order. It runs the first true block and skips the rest. ## Truthy and Falsy Values JavaScript treats non-boolean values as true or false: ```javascript // Falsy — treated as false false, 0, "", null, undefined, NaN // Truthy — treated as true true, 1, -1, "hello", " ", [], {}, function(){} ``` **Remember:** An empty array `[]` is truthy, even though it has no elements. ```javascript let name = "John"; // Direct truthy check — cleaner if (name) { console.log("Name exists"); } ``` ## Ternary Operator Short if/else for simple conditions: ```javascript let age = 18; let status = age >= 18 ? "Adult" : "Minor"; ``` Format: `condition ? valueIfTrue : valueIfFalse` ## Complete Example: Login Check ```javascript let username = null; let isLoggedIn = false; let isAdmin = false; if (!username) { console.log("Please log in"); } else if (!isLoggedIn) { console.log("Account not active"); } else if (isAdmin) { console.log("Welcome, Admin!"); } else { console.log("Welcome, User!"); } ``` ## Best Practices 1. **Use strict equality** — `===` prevents type coercion bugs 2. **Use early returns** — Reduce nesting 3. **Keep conditions simple** — Break complex logic apart 4. **Use ternary for simple cases** — Don't overcomplicate 5. **Understand truthy/falsy** — Prevents unexpected behavior ## Common Mistakes 1. **Using `==` instead of `===`** — Type coercion causes bugs 2. **Forgetting `else`** — No fallback case 3. **Deep nesting** — Hard to read and maintain 4. **Confusing truthy/falsy** — `0` and `""` are falsy 5. **Assignment in condition** — Use `===` not `=`
No changes yet
Reset to original
Submit suggestion
cancel