babel / babel/babel

[plugin-transform-for-of] Ability to opt in or out of for-of loose mode

Open
#9,915 2 comments 0 reactions 0 assignees View on GitHub
i: needs triage
Dominant language
TypeScript
Stars
44k
Forks
6k
Avg merge
5d 15h
Merged PRs (30d)
23

Description

## Feature Request

**Is your feature request related to a problem? Please describe.**

Loose mode is nice, even though my target environments support for-of, I'd like to keep using loose mode to have faster iteration on arrays with convenient for-of syntax.

But sometimes, in rare cases, I may want to take advantage of native for-of in order to edit arrays in place while iterating (including adding or deleting items), but this doesn't work in loose mode for obvious reasons.

**Describe the solution you'd like**

It'd be nice to have a comment that can enable (or disable) loose for-of. F.e. If we're in loose mode, we could write the following to enable strict mode (it may compile, or may simply output the for-of as-is depending on `env` config):

```js
// @babel no-loose
for (const item of array) {
// ...
}
```

Not sure about the comment format, but you get the idea.

Conversely, someone with loose mode turned off might want to do

```js
// @babel loose
for (const item of array) {
// ...
}
```

The `no-*` could be a generic commenting mechanism to disable/enable some feature.

**Describe alternatives you've considered**

I can opt for the strict mode by converting an array into a Set, for example. But it seems clunky.

**Teachability, Documentation, Adoption, Migration Strategy**

...

---

Sidenote, in my tests, the following hand-written version I've been using,

```js
var arr = [1, 2, 3];
for (let i = 0, l = arr.length; i < l; i+=1) {
var a = arr[i];
}
```

is almost three times faster than Babel's output.

```js
var _arr = [1, 2, 3];
for (var _i = 0; _i < _arr.length; _i++) {
var a = _arr[_i];
}
```

Contributor guide

Open the contributing guide

Research direction

Start with the plugin-transform-for-of implementation and its existing loose-mode behavior. Compare the requested per-loop loose and no-loose examples, then define how the comment mechanism should interact with the configured mode. Done means the opt-in and opt-out behavior is implemented consistently, with coverage for both configuration directions.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.