Skip to content

Recommendation against use of for...in for array iteration. #40

@noahlange

Description

@noahlange

Howdy, love the library.

Running into some issues regarding your use of the for...in statement for array iteration. for...in is for enumerable properties of collections, not iteration through iterables (e.g. Arrays). I'd recommend using array.forEach(), for...of (broadly supported by Node >= 0.12, dunno about browser compat.) or a standard for loop, which is obviously more verbose but more appropriate than for...in.

for...in will throw when some dingus (not me, but there are lots of dinguses out there) modifies the Array prototype, because for...in will kick back any additional enumerable properties, not just the elements of the array.

Copy-pasta'd some relevant code from the MDN demonstrating the issue.

Object.prototype.objCustom = function () {}; 
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

Add Array.prototype.foo = () => 'bar' to index.js and run the test suite. It'll run through all the places where that needs to be changed.

Cheers!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions