ampproject / ampproject/rollup-plugin-closure-compiler

Transform [].forEach => for-in

Open
#124 1 comment 0 reactions 1 assignee Claimed by @kristoferbaxter View on GitHub
Dominant language
TypeScript
Stars
293
Forks
28
PR merge metrics
No merged PRs in 30d

Description

## Is your feature request related to a problem? Please describe.
Many `[].forEach` calls can be converted to a `for...in` safely.

```javascript
const LANGUAGES = { javascript, json, xml };
Object.keys(LANGUAGES).forEach( key => hljs.registerLanguage(key, LANGUAGES[key]) );
```

Can be converted to...
```javascript
const LANGUAGES = { javascript, json, xml };
for (key in LANGUAGES) { hljs.registerLanguage(key, LANGUAGES[key]) }
```

## Describe the solution you'd like
This transform can be done safely so long as the inner function doesn't rely on `this` being auto bound.

It's worth investigating if there are cases where a function call can be generated that passes the scope as an argument and leverages it correctly as well.

## Describe alternatives you've considered
Ignore this transform entirely.

**Edit**: If order is important, `for...of` is a better choice.
>Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.