Control Flow
Intro to Control Flow
Control flow is how programs make decisions and repeat work. Without it, code
would just run straight through from top to bottom.
Conditionals
The
if statement runs code only when a condition is true:if (temperature > 30) {
console.log("It's hot!")
}
Add
else for an alternative:if (temperature > 30) {
console.log("It's hot!")
} else {
console.log("It's comfortable")
}
Chain conditions with
else if:if (temperature > 30) {
console.log("It's hot!")
} else if (temperature > 20) {
console.log("It's warm")
} else {
console.log("It's cool")
}
Switch Statements
When comparing one value against many specific options,
switch is cleaner than
a long if/else if chain:switch (day) {
case 'Monday':
console.log('Start of week')
break
case 'Friday':
console.log('Almost weekend!')
break
default:
console.log('Regular day')
}
Loops
Loops repeat code multiple times:
for loop - When you know how many times:for (let i = 0; i < 5; i++) {
console.log(i)
}
while loop - When you don't know how many times:while (condition) {
// Keep going until condition is false
}
do...while loop - When you want to run the code at least once:do {
// Keep going until condition is false
} while (condition)
for...in loop - When you want to iterate over the properties of an object:for (const key in object) {
// Keep going until condition is false
}
for...of loop - When you want to iterate over the values of an iterable:for (const value of iterable) {
// Keep going until condition is false
}
for...await...of loop - When you want to iterate over the values of an async iterable:for await (const value of asyncIterable) {
// Keep going until condition is false
}
Ternary Operator
The ternary operator is a concise way to choose between two values:
const status = age >= 18 ? 'adult' : 'minor'
It has three parts: condition, value if true, value if false.
Error Handling
Sometimes code needs to stop early when something goes wrong. You can throw
an error to interrupt normal flow, and catch it to recover:
try {
const parsedValue = Number('not-a-number')
if (Number.isNaN(parsedValue)) {
throw new Error('Invalid number')
}
} catch (error) {
console.error(error)
}
TypeScript's type narrowing works inside conditionals. When you check a type,
TypeScript knows the more specific type inside that block.
In this exercise, you'll use control flow to build real features.