0Pricing
JavaScript Academy · Lesson

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
Early Returns and Guard Clauses — illustration 1

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("");
Early Returns and Guard Clauses — illustration 2

All lessons in this course

  1. if/else and switch — core patterns
  2. Loops: for, while, do…while, for…of vs for…in
  3. Early Returns and Guard Clauses
← Back to JavaScript Academy