Jese Leos

Returning from a JavaScript Loop with Some

I am working on the Revision1 functionality for PhrontPage (autosave + history). After getting the main pieces in place, I realized that you likely do not want revisions on new content until you reach a short minimal threshold (starting at 30 characters). So I added a quick check for the length of the markdown field, but that felt dirty hardcoding a specific field.

Next, I added a target(s) to my Stimulus controller. Now, any field with the target applied can be evaluated—there are no hardcoded field names, etc.

However, I could not for my life see why the following function was not returning true.

hasFieldsWithoutMinimalLength() {
  this.minimalLegthFieldTargets.forEach(field => {
    if (field.value.length < this.minimalLengthValue) {
      return true
    }
  })
  return false
}

In the golden age of programming (6 months or so ago), this would have resulted in a Google search or two, scrolling through Stack Overflow, or perhaps the X/Twitter hail mary. However, today, I can ask Claude via SuperMaven

(me) The function that starts on line #37, hasFieldsWithoutMinimalLength appears to iterate fine, but the return in line 40 is not stopping the function from returning false

And you get the following:

(Claude) You're correct in identifying the issue with the hasFieldsWithoutMinimalLength function. The problem is that the return true statement is inside the forEach loop, which doesn't actually stop the function's execution or return from the outer function. Instead, it only returns from the callback function passed to forEach.

I know there are folks generating whole applications, etc., but for me, this is a sweet spot. I enjoy writing code, the journey, and the act of creating2. Having AI there to point out my obvious or sometimes subtle bugs is an amazing boost to my productivity.

For those curious, here is the fix and why.

hasFieldsWithoutMinimalLength() {
  return this.minimalLegthFieldTargets.some(field =>
    field.value.length < this.minimalLengthValue
  )
}

The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise, it returns false. It doesn't modify the array.

  1. Technically, I am babysitting an Elastic Search migration that has me rethinking my career choices

  2. No shade. You do you and find what/how/etc you enjoy. Shipping is awesome, and if generating code and ignoring it all makes that happen, go for it.