ES2020 contains a new String.prototype.matchAll
method, which returns an iterator. I'm sure I'm missing something dumb/obvious, but I don't see why it doesn't just return an array instead.
Can someone please explain the logic there?
EDIT: Just to clarify something from the comments, I'm operating on the assumption that iterators haven't simply replaced arrays as the new way all JS APIs going forward will return multiple values. If I missed that memo, and all new JS functions do return iterators, a link to said memo would 100% qualify as a valid answer.
But again, I suspect that such a blanket change wasn't made, and that the makers of Javascript made a specific choice, for this specific method, to have it return an iterator ... and the logic of that choice is what I'm trying to understand.
exec
, which we used to use instead of matchAll to get the same functionality, since withg
flag in match you won't be able to get all the matches as you can get inexec
to mimic same functionality it is proposed. – Daguerreexec
returns an Array, not an iterator. From the MDN: "The exec() method executes a search for a match in a specified string. Returns a result array, or null." – EnneagonMDN
– DaguerrematchAll
should return, instead of an array?" – Enneagongoing against the trend of previous regex stuff
just because old functions that were defined before iterators exist, does not mean that new functions should/must not utilize iterators. And changingexec
to return an iterator is not possible.no new function should ever return an array now that iterators exist
, for certain tasks you can estimate well how large the result will be, and how long it will take to calculate. FormatchAll
it depends on the regular expression and the input, so having a function that allows to not fully parse the result can indeed be helpful. – Samp