davidmerfield / Typeset

An HTML pre-proces­sor for web ty­pog­ra­phy
https://typeset.lllllllllllllllll.com/
Creative Commons Zero v1.0 Universal
2.41k stars 52 forks source link

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

Open noahlange opened 8 years ago

noahlange commented 8 years ago

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!