Course contentsShow
← JavaScript
Lesson 1898 of 2,72340. PerformanceFree lesson

Early Returns and Short-Circuiting

Reduce unnecessary work by exiting loops and functions as soon as the answer is found rather than processing everything.

Early Returns and Short-Circuiting

You'll learn how to make your code faster by stopping work the moment you have your answer.

The Core Idea

Imagine searching for your keys in a house with 10 rooms. Once you find them in room 3, you don't keep searching rooms 4 through 10 — you stop immediately. The same principle applies to code: exit functions and loops as soon as you've found what you need, rather than continuing pointless work.

This is called early returning in functions and short-circuiting in loops.

Early Returns in Functions

// Bad: checks all conditions even when unnecessary
function canUserPost(user) {
  let result = true;
  if (!user) result = false;
  if (!user.isActive) result = false;
  if (user.isBanned) result = false;
  return result;
}

// Good: exit immediately when answer is clear
function canUserPost(user) {
  if (!user) return false;
  if (!user.isActive) return false;
  if (user.isBanned) return false;
  return true;
}

The second version stops checking the moment it knows the answer is "false."

Short-Circuiting in Loops

// Bad: always checks all 10,000 items
function hasAdmin(users) {
  let found = false;
  for (let i = 0; i < users.length; i++) {
    if (users[i].role === 'admin') found = true;
  }
  return found;
}

// Good: stops at first match
function hasAdmin(users) {
  for (let i = 0; i < users.length; i++) {
    if (users[i].role === 'admin') return true;
  }
  return false;
}

If there's an admin at position 5 in a 10,000-user array, why check the remaining 9,995 items?

Key Takeaway: Exit functions and loops the instant you have your answer — every line of code you skip is performance you gain.