DEV Community

Cover image for If you gaze long into an abyss, the abyss also gazes into you, avoiding the empty void in JS
Marcos Henrique
Marcos Henrique

Posted on • Edited on

3 1 1

If you gaze long into an abyss, the abyss also gazes into you, avoiding the empty void in JS

Recently, I came across an interesting scenario while working with list checks in JS, So have a gaze at the following code:

appointment.serviceRequests?.every(
  serviceRequest => serviceRequest.createdMethod === ServiceRequestMethods.INTEGRATED,
);
Enter fullscreen mode Exit fullscreen mode

At first glance, it seems like we're checking if all serviceRequests in an appointment were created using a specific method (INTEGRATED). However, there's a subtle issue here: what if serviceRequests is an empty list? 🤔

What happens?

In JavaScript, the .every() method returns true for empty lists. This happens because, when there are no elements to check, the statement is considered "vacuously true" (a concept from mathematical logic).
In other words, since there are no elements to contradict the condition, the result is true.

This can lead to unexpected behaviour. For example, if serviceRequests is [] (an empty list), the code above will return true, even though there are no serviceRequests to validate.

How do you think we could fix it?
We can add a check to avoid this behaviour to ensure the list is not empty before using .every(). Here's the solution:

appointment?.serviceRequests?.length &&
appointment.serviceRequests?.every(
  serviceRequest => serviceRequest.createdMethod === ServiceRequestMethods.INTEGRATED,
);
Enter fullscreen mode Exit fullscreen mode

Here, we:

Check if serviceRequests exists and is not empty (appointment?.serviceRequests?.length).

Apply .every() only if the list is not empty.

Why does this matter?

Understanding these details is crucial for writing robust code and avoiding subtle bugs. The concept of "vacuously true" can be useful in many contexts, but it can also be confusing if not handled properly.

💡 Tip: Always consider edge cases, such as empty lists, when writing conditional checks.
Have you encountered something similar? Share your experiences in the comments! 👇

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay