Conditionals
if, else, ternary, switch
Skills taught: js.conditionals, js.if-else, js.ternary, js.switch
if / else if / else
const score = 75;
if (score >= 90) {
console.log('A — Excellent!');
} else if (score >= 75) {
console.log('B — Good job!');
} else if (score >= 60) {
console.log('C — Keep going!');
} else {
console.log('Below passing — try again.');
}
// Output: 'B — Good job!'
Truthy and falsy
// Falsy values — evaluate to false in an if condition
if (0) { /* never runs */ }
if ('') { /* never runs */ }
if (null) { /* never runs */ }
if (undefined) { /* never runs */ }
if (false) { /* never runs */ }
if (NaN) { /* never runs */ }
// Truthy — everything else
if (1) { /* runs */ }
if ('hello') { /* runs */ }
if ([]) { /* runs — empty array is truthy! */ }
if ({}) { /* runs — empty object is truthy! */ }
// Common pattern: check if a value exists
const user = getCurrentUser();
if (user) {
showDashboard(user);
} else {
showLoginPage();
}
Ternary operator
// condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status); // 'adult'
// Useful in JSX/template literals
const greeting = `Good ${hour < 12 ? 'morning' : 'afternoon'}!`;
// AVOID nesting ternaries — use if/else instead
// Bad:
const grade = score >= 90 ? 'A' : score >= 75 ? 'B' : 'C';
// Better:
let grade;
if (score >= 90) grade = 'A';
else if (score >= 75) grade = 'B';
else grade = 'C';
switch statement
const day = 'Monday';
switch (day) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
console.log('Weekday');
break; // stop — don't fall through
case 'Saturday':
case 'Sunday':
console.log('Weekend');
break;
default:
console.log('Unknown day');
}
// Output: 'Weekday'
// Modern alternative — object lookup (often cleaner)
const labels = {
Monday: 'Weekday', Tuesday: 'Weekday',
Saturday: 'Weekend', Sunday: 'Weekend',
};
console.log(labels[day] ?? 'Unknown'); // 'Weekday'
Frequently Asked Questions
When should I use switch instead of if/else if?
switch is cleaner when you are comparing one variable against many discrete values (day names, status codes). if/else is better when conditions involve ranges, multiple variables, or complex logic.
What is an early return and why is it useful?
Returning early from a function when a condition is not met avoids deeply nested if/else. Instead of if (valid) { ... lots of code ... }, write if (!valid) return; and continue with the happy path at the same indentation level.