---
title: "Early Returns and Intermediate Variables in JavaScript"
description: "Intermediate variables name each step of complex logic, and early returns handle failing cases first. A JavaScript authentication check, rewritten both ways."
canonical: "https://www.trevorlasn.com/blog/embrace-early-returns-and-intermediate-variables-for-readable-code"
author: "Trevor I. Lasn"
published: "2024-08-30"
last-updated: "2024-08-30"
topics: ["JavaScript", "Software engineering"]
---

# Early Returns and Intermediate Variables in JavaScript

Intermediate variables name each step of complex logic, and early returns handle failing cases first. A JavaScript authentication check, rewritten both ways.

By Trevor I. Lasn · Published 2024-08-30 · https://www.trevorlasn.com/blog/embrace-early-returns-and-intermediate-variables-for-readable-code

Writing readable code is tough, but it’s worth it. Start by using intermediate variables. These variables break down complex logic into simple, understandable steps.

Let’s say you’re building a function to handle user authentication. The function needs to check several things: whether the username and password are correct *(1)*, whether the account is active *(2)*, and whether the user has agreed to the latest terms of service *(3)*. 

```javascript
if (isCorrectPassword(username, password)
    && isAccountActive(username)
    && hasAgreedToTerms(username)) {
    // Proceed with login
}
```

This might do the job. But imagine you need to add more conditions later on. Suddenly, the if-statement becomes harder to read and maintain. Each new condition adds another layer of complexity.

### Simplify with Intermediate Variables

One way to clean up this code is by introducing intermediate variables with meaningful names.

```js
const isAuthenticated = isCorrectPassword(username, password);
const isActive = isAccountActive(username);
const isCompliant = hasAgreedToTerms(username);

if (isAuthenticated && isActive && isCompliant) {
    // Proceed with login
}
```

Now, instead of trying to parse a long *if-statement*, you can see at a glance what the code is checking for. The logic is the same, but the readability is greatly improved.

Consider a scenario where you need to process a user’s order. The order should only be processed if the user is logged in *(1)*, the cart isn’t empty *(2)*, and the payment method is valid *(3)*.

```js
const isLoggedIn = checkUserLogin(user);
const hasItemsInCart = cart.items.length > 0;
const isPaymentValid = validatePaymentMethod(user.paymentMethod);

if (isLoggedIn && hasItemsInCart && isPaymentValid) {
    // Process the order
}
```

With these intermediate variables, anyone reading the code can quickly understand the preconditions for processing an order.

### The Power of Early Returns

Code doesn’t have to be a puzzle for the next person who reads it. Readable code is key, and early returns let you zero in on the important parts of your logic without getting lost in unnecessary details.

Nested *if-statements* make code harder to follow. Let’s look at a common pattern.

```js
if (isAuthenticated) {
    if (isActive) {
        if (isCompliant) {
            // Proceed with login
        }
    }
}
```

We can all agree this is a horrible approach. Deeply nested structures that are difficult to manage, especially as more conditions are added. Instead, use early returns to flatten the structure and make the code easier to read.

```js
if (!isAuthenticated) return;
if (!isActive) return;
if (!isCompliant) return;

// Proceed with login
```

With early returns, you immediately exit the function when a condition isn’t met. This allows you to focus on the main task without unnecessary nesting.

### Why Early Returns Make Sense

Early returns help keep your code simple and to the point. This approach is particularly useful in real-world applications where functions can have many preconditions.

```js
function submitForm(data) {
    if (!data.name) return 'Name is required';
    if (!data.email) return 'Email is required';
    if (!isValidEmail(data.email)) return 'Email is invalid';

    // Submit the form
    sendToServer(data);
    return 'Form submitted successfully';
}`
```

Inside the `submitForm` function, we're checking for missing or invalid fields and return early if something is wrong. The rest of the function is only concerned with the actual submission.

By using early returns and intermediate variables, you can transform complex, hard-to-read code into something much more manageable.
