EasyJavaScriptTypeScript

Early Return

Clean CodeReadabilityRefactoring

Deep nesting is hard to read. Replace nested if blocks with guard clauses that return early.

// dirty — 4 levels deep
function solve(user) {
  if (user) {
    if (user.isActive) {
      if (user.age >= 18) {
        if (user.hasPremium) {
          return 'full-access';
        } else {
          return 'basic-access';
        }
      } else {
        return 'age-restricted';
      }
    } else {
      return 'inactive';
    }
  } else {
    return 'no-user';
  }
}

Refactor using guard clauses so the happy path is at the end with minimal nesting.

Sample tests

Test #1null user
Input: [null]
Output: "no-user"
Test #2undefined user — treat as absent
Input: [null]
Output: "no-user"
Test #3Inactive user
Input: [{"age":25,"isActive":false,"hasPremium":true}]
Output: "inactive"
Test #4Under 18
Input: [{"age":16,"isActive":true,"hasPremium":true}]
Output: "age-restricted"
Test #5Adult, no premium
Input: [{"age":18,"isActive":true,"hasPremium":false}]
Output: "basic-access"
Test #6Full access
Input: [{"age":30,"isActive":true,"hasPremium":true}]
Output: "full-access"