Skip to content

Instantly share code, notes, and snippets.

@kamauwashington
Last active September 4, 2022 23:33
Show Gist options
  • Save kamauwashington/63a233a47b7a3651b6a3e93938b6c85c to your computer and use it in GitHub Desktop.
Save kamauwashington/63a233a47b7a3651b6a3e93938b6c85c to your computer and use it in GitHub Desktop.

TypeScript Bits

Use for..of in lieu of traditional incremental for loops when appropriate

TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner, to intermediate, to ninja, these bits are for you 😄


Estimated reading time : 2 minutes

For loops are for loops, sure. There is absolutely nothing wrong with the traditional incremental iterator approach. However, this recommendation is about readability, maintenance, decreasing code smells, as well as best practice when using loops in TypeScript (and in this case ES6+ as well). Often during code review one will find references to an item via its parent array and index numerous times (think myArray[i].firstName and guess how lastName is accessed? :disappointed:). It is a best practice in most if not all languages to create a variable out of this value accessed by index once.

The example below illustrates for..of in TS and ES6+

Before

const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
for (let i=0;i<workingArray.length;i++) {
  console.log(workingArray[i]);
}

After

const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
for (const item of workingArray) {
  console.log(item);
}

But wait! I may need an index as well as the individual item!

it is so awesome that someone thought about this beforehand!

const workingArray : Array<number> = [0,1,2,3,4,5,6,7,8,9];
for (const [index,item] of workingArray.entries()) {
  console.log(`${item} has an index of ${index}`);
}

Notes

  • for..of and for..in are not the same. for..of is for items in an arrray, for..in is for properties of an object. It is syntactically confusing when said aloud admittedly 😕
  • utilize const and let keywords where appropriate, to explicitly define mutability pre-transpilation, and prevent simple coding mistakes.
  • for..of gets transpiled to the incremental iterator style when targeting < ES6 for backwards compatibility
  • Why use for..of over Array.prototype.forEach? Each has its own use case. However, at the time of authoring, it is not possible to stop or break a forEach without throwing an exception which is not always desirable.
  • INSIGHT: A reverse iterator is missing IMHO, as it is not always desirable to reverse an array then loop. A reverse iterator would be the equivalent of traditional for loops with i--;

Visit the TypeScript Deep Dive on for..of for more in-depth information!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment