DEV Community

loading...
Cover image for For...of Loop Refactoring
P42

For...of Loop Refactoring

Lars Grammel
Creating automatic refactoring tools for TypeScript and JavaScript. Founder of http://p42.ai
・1 min read

for...of loops over iterable objects, for example arrays or strings.

The for...of loop is easier to read than indexed for loops and can replace them in many cases.

For example,

for (let i = 0; i < elements.length; i++) {
    const element = elements[i];
    console.log(element);
}

Enter fullscreen mode Exit fullscreen mode

can be replaced by

for (const element of elements) {
    console.log(element);
}
Enter fullscreen mode Exit fullscreen mode

For..of loops have been introduced with ES6. Learn More: for...of (MDN)

P42 now supports converting regular for-loops over arrays with index variables into more concise for-of loops. The refactoring is available on the playground and for all repositories. Try it out!

Discussion (0)