Module 3: Conditions and Loops
Conditional Statements
Use if, else if, else, and switch to express decisions.
Conditional statements choose which branch to execute based on an expression's truthiness.
const score = 82;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Good");
} else {
console.log("Keep practising");
}
Conditions are checked from top to bottom. Put the most appropriate conditions in an order that prevents a broad condition from hiding a more specific one.
switch#
Use switch when comparing one expression against several discrete cases:
const role = "editor";
switch (role) {
case "admin":
console.log("Full access");
break;
case "editor":
console.log("Can edit content");
break;
default:
console.log("Read-only access");
}
The break statements prevent execution from falling through to the next case. Intentional fall-through should be documented. For many simple mappings, an object lookup can be easier to maintain than a long switch.
Avoid deeply nested logic#
Return early from functions when a condition means there is nothing more to do. This can reduce indentation and make validation steps easier to scan.
Practice#
Write a grading function that returns a label for a numeric score, and handle invalid scores explicitly.