Vanta Logo
SPONSOR
Automate SOC 2 & ISO 27001 compliance with Vanta. Get $1,000 off.
Up to date
Published
3 min read

Trevor I. Lasn

Staff Software Engineer, Engineering Manager

Embrace Intermediate Variables and Early Returns in JavaScript

Early returns and intermediate variables make your code easier to reason about

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).

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.

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).

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.

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.

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.

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.

If you found this article helpful, you might enjoy my free newsletter. I share developer tips and insights to help you grow your skills and career.


More Articles You Might Enjoy

If you enjoyed this article, you might find these related pieces interesting as well. If you like what I have to say, please check out the sponsors who are supporting me. Much appreciated!

Javascript
7 min read

WeakRefs in JavaScript: Explained In Simple Terms

Understanding how WeakRef helps manage memory in JavaScript

Jan 7, 2025
Read article
Javascript
6 min read

setImmediate() vs setTimeout() in JavaScript

both setImmediate() and setTimeout() are used for scheduling tasks, but they work differently.

Sep 8, 2024
Read article
Javascript
7 min read

JavaScript Sets and Maps: Beyond Arrays and Objects

How to handle unique values and key-value pairs properly without type coercion and performance issues

Nov 17, 2024
Read article
Javascript
6 min read

AggregateError in JavaScript

AggregateError helps you handle multiple errors at once in JavaScript. This makes your code easier to manage and more reliable.

Sep 2, 2024
Read article
Javascript
4 min read

The Only Widely Recognized JavaScript Feature Ever Deprecated

The 'with' statement is the only feature ever deprecated in JavaScript

Aug 22, 2024
Read article
Javascript
3 min read

JavaScript's &&= Operator: Understanding Logical AND Assignment

Use the &&= operator to safely update truthy values while preserving falsy states

Nov 5, 2024
Read article
Javascript
5 min read

Precise Decimal Math in JavaScript with Fraction.js

How to handle exact decimal calculations in JavaScript when floating-point precision isn't good enough

Nov 16, 2024
Read article
Javascript
4 min read

Intl.DurationFormat: Format Time Durations with Locale Support

Stop writing manual duration formatting code. Instead, leverage the new powerful Intl.DateTimeFormat API for internationalized time displays

Mar 13, 2025
Read article
Javascript
5 min read

Working with JavaScript's Scheduler API

Learn how to prioritize and control task execution in JavaScript using the new Scheduler API for better performance and user experience

Nov 26, 2024
Read article

Become a better engineer

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Many companies have a fixed annual stipend per engineer (e.g. $2,000) for use towards learning resources. If your company offers this stipend, you can forward them your invoices directly for reimbursement. By using my affiliate links, you support my work and get a discount at the same!


This article was originally published on https://www.trevorlasn.com/blog/embrace-early-returns-and-intermediate-variables-for-readable-code. It was written by a human and polished using grammar tools for clarity.