DEV Community

Cover image for For...of Loop Refactoring
Lars Grammel for P42

Posted on • Updated on • Originally published at p42.ai

For...of Loop Refactoring

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 in the P42 VS Code Extension!

Top comments (0)