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,
);
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,
);
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! 👇
Top comments (0)