Early Returns and Guard Clauses
Use early returns and guard clauses to simplify conditions, reduce nesting, and make the happy path clear.
Intro
Goal: Write clearer functions by returning early for invalid inputs so the happy path stays short.
- Early return
- Guard clause
- Less nesting

Without guard clause
Nesting pushes the main work inside an if, which can grow hard to read.
// Nested style without guard
function welcome(name) {
if (name) {
const message = "Hello, " + name + "!";
console.log(message);
} else {
console.log("Name required");
}
}
welcome("Ayla");
welcome("");

All lessons in this course
- if/else and switch — core patterns
- Loops: for, while, do…while, for…of vs for…in
- Early Returns and Guard Clauses