If you mean by setting its .length
to the current index in the iteration, then yes, it's "valid", but be aware that in doing so, you're clearing any Array members from that point forward.
var arr = ["foo","bar","baz"];
console.log(arr.length); // 3
arr.forEach(function(v, i) {
if (i == 1)
arr.length = i;
else
console.log(v);
});
console.log(arr.length); // 1
If you set the .length
to false
, you're effectively setting it to 0
, and so you're clearing the entire Array.
Using .some
or .every
seems more sensible to me.
I should note that the iteration doesn't necessarily stop, but your callback won't be invoked because the native .forEach()
does not invoke the callback for non-existent properties. According to the spec, the length in cached.
This can be tested by expanding the Array during the iteration. The added members are never reached.