Control Flow, Conditions, and Loops
Control flow is the order in which statements are executed in a program. In this guide, we will cover how to dynamically route code execution based on conditions and how to repeat operations using loops.
1. Conditional Statements
A. if, else if, and else
The standard decision-making statement.
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}B. switch Statement
Used for multi-branch selections based on the strict equality (===) of a value.
let role = "admin";
switch (role) {
case "admin":
console.log("Full access");
break;
case "editor":
console.log("Can edit content");
break;
case "guest":
console.log("Read only");
break;
default:
console.log("Unknown role");
}Note: Always include break inside case statements to prevent code from falling through to the next case.
2. Truthy and Falsy Values
In JavaScript, any value can be evaluated in a boolean context (like an if condition).
Falsy Values
There are exactly 8 falsy values in JavaScript that evaluate to false when cast to boolean:
false0(and-0,0nin BigInt)""(Empty string)nullundefinedNaN
Truthy Values
Everything else is truthy. This includes arrays, objects, functions, and non-empty strings.
let items = []; // Empty array
if (items) {
console.log("This will print! Empty arrays are truthy.");
}3. Loops
Loops are used to execute a block of code repeatedly as long as a specified condition is met.
A. for Loop
Best when you know in advance how many times the loop should run.
for (let i = 0; i < 5; i++) {
console.log(`Iteration: ${i}`);
}B. while Loop
Repeats code as long as a condition is true. The condition is checked before executing the loop body.
let count = 0;
while (count < 3) {
console.log(`Count: ${count}`);
count++;
}C. do...while Loop
Similar to the while loop, but the condition is checked after executing the loop. This guarantees the block runs at least once.
let number = 10;
do {
console.log("This executes once even though condition is false.");
} while (number < 5);4. Loop Interruptions: break and continue
break: Instantly terminates the loop and jumps out of it.continue: Skips the rest of the current iteration and jumps to the next evaluation.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skip 3
if (i === 5) break; // Stop loop at 5
console.log(i); // Prints: 1, 2, 4
}In the next module, we will explore functions, arguments, return values, and scopes in JavaScript.