Conditionals
EasyConditionals let your code make decisions. JavaScript has if/else, switch, and the ternary operator (?:). Understanding truthiness is key: JS converts values to booleans in conditions.
Interactive Visualization
if (age >= 21) {console.log("Can drink");} else if (age >= 18) {console.log("Can vote");} else {console.log("Too young");}
Output:
"Can vote"Key Points
- if/else: most common, can chain with else if
- switch: compare one value against many cases
- Ternary: condition ? valueIfTrue : valueIfFalse
- Falsy values: false, 0, "", null, undefined, NaN
- Everything else is truthy (including [], {}, "0")
Code Examples
if/else Statement
const age = 18; if (age >= 21) { console.log("Can drink"); } else if (age >= 18) { console.log("Can vote"); } else { console.log("Too young"); } // Output: "Can vote"
Conditions are checked top to bottom, first true wins
Ternary Operator
const age = 20; // condition ? ifTrue : ifFalse const status = age >= 18 ? "adult" : "minor"; // status = "adult" // Nested ternary (use sparingly!) const drink = age >= 21 ? "beer" : age >= 18 ? "coffee" : "juice";
Ternary is great for simple conditional assignments
switch Statement
const day = "Monday"; switch (day) { case "Monday": case "Tuesday": console.log("Work day"); break; // Important! Without break, falls through case "Saturday": case "Sunday": console.log("Weekend!"); break; default: console.log("Midweek"); }
switch uses strict equality (===) and needs break
Truthiness
// Falsy values (evaluate to false) if (false) {} if (0) {} if ("") {} if (null) {} if (undefined) {} if (NaN) {} // Truthy (everything else!) if ("0") {} // true! Non-empty string if ([]) {} // true! Empty array if ({}) {} // true! Empty object
Only 6 values are falsy, everything else is truthy
Common Mistakes
- Forgetting break in switch (causes fall-through)
- Thinking [] or {} are falsy (they're truthy!)
- Using == instead of === in conditions
Interview Tips
- Know all 6 falsy values by heart
- Explain why [] and {} are truthy
- Show when to use ternary vs if/else