Skip to content

Latest commit

 

History

History
48 lines (36 loc) · 827 Bytes

no-for-in-loops.md

File metadata and controls

48 lines (36 loc) · 827 Bytes

No for-in loops

Rationale

For-in loops are weird, and behave erratically over both arrays and objects.

  • For arrays, they behave weirdly if there are any sparse indexes.
  • For objects, they also loop over keys in the prototype chain. And who needs that?

Good

for (let item of myArray) {
    console.log(item);
}
for (let i = 0, i < myArray.length; i++) {
    console.log(i, myArray[i]);
}
for (let key of Object.keys(myObject)) {
    console.log(key, myObject[key]);
}

Bad

for (let i in myArray) {
    console.log(i, myArray[i]);
}
for (let key in myObject) {
    if (myObject.hasOwnProperty(key)) {
        console.log(key, myObject[key]);
    }
}

Discussion

#1