Control Flow: if, else, and switch
Control Flow: if, else, and switch
~10 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
With control flow, our budget app decides how to react to different values – for instance, whether a transaction is income or an expense.
if, else if, else
const amount = -850;
if (amount > 0) {
console.log('Income');
} else if (amount < 0) {
console.log('Expense');
} else {
console.log('Neutral (0)');
}
// Output: ExpenseThe condition in if(...) doesn't need to be a real boolean – as explained in chapter 5, JavaScript coerces ANY value into a truth value via truthy/falsy.
The ternary operator: compact if/else expressions
For simple cases where a VALUE (not a statement) is picked based on a condition, the ternary operator condition ? ifTrue : ifFalse is the more compact alternative:
const amount = -850;
const kind = amount > 0 ? 'Income' : 'Expense';
console.log(kind); // 'Expense'Tipp: Rule of thumb: ternary operator for simple single-line value assignments, if/else for anything with multiple statements or nested logic. Nested ternaries (a ? b : c ? d : e) are hard to read – avoid them.
switch: several fixed cases
When a single value is checked against SEVERAL fixed possibilities, switch is often more readable than a long if/else if chain:
const category = 'Rent';
let icon;
switch (category) {
case 'Rent':
icon = '????';
break;
case 'Salary':
icon = '????';
break;
case 'Leisure':
icon = '????';
break;
default:
icon = '????';
}
console.log(icon); // '????'Achtung: The break after each case is CRUCIAL – without it, execution "falls through" into the NEXT case, even if its condition doesn't match. This behavior is sometimes intentional (several cases share the same code), but is usually a bug. Note that switch internally compares with ===, not ==.
A first category icon function
With this, we now have the tools to assign an icon to each of our budget app's expense categories – we'll build a function for that in chapter 8, once we know functions.