josdejong/mathjs

document iterator for Matrix classes (since they allow short-circuit unlike `forEach()`)

Open

#3558 opened on Oct 17, 2025

View on GitHub
 (4 comments) (0 reactions) (0 assignees)JavaScript (13,832 stars) (1,298 forks)batch import
documentationgood first issue

Description

At the moment, the callback in a forEach() invocation is simply called and its return value is ignored. However, some operations one might execute using forEach(), especially those of the nature of searching for an entry with a desired property, could benefit from the ability to terminate the iteration over the elements early.

Therefore, I would suggest having some sentinel value that could be returned from a forEach callback that would mean the iteration should terminate. Some possibilities:

  • Any truthy value. Note this might break existing code, if there are callbacks out there that don't want to terminate, but happen to return a truthy value.
  • A special Symbol generated for the purpose. This would not break existing code.
  • A plain object {terminate: true}. This is unlikely to break existing code, and allows the possibility of specifying a return value as well. (The more-complicated version of this option would use a special Symbol in place of true as the value of the terminate key to make it impossible to break existing code.)

In addition, we could allow the forEach function to return a value based on the return value of the callback. Some possibilities:

  • The return value of the callback the last time it is called is returned from forEach.
  • The last time the callback returns a plain object with key return, the value of that key is returned.

If the last option in each of the bullets above were adopted, then a callback could return {terminate: true, return: 0} to stop the iteration and return 0 from the forEach call (for example). Note choosing the first option from each bullet point would allow forEach to terminate and return a truthy value, but there would be no way to terminate and return a falsy value.

Contributor guide