Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no-array-for-each: Add more reasoning to the docs #2183

Merged
merged 1 commit into from
Aug 17, 2023
Merged

no-array-for-each: Add more reasoning to the docs #2183

merged 1 commit into from
Aug 17, 2023

Conversation

Zamiell
Copy link
Contributor

@Zamiell Zamiell commented Aug 4, 2023

n/a

@sindresorhus sindresorhus changed the title docs: add more reasoning no-array-for-each: Add more reasoning to the docs Aug 5, 2023
@Zamiell
Copy link
Contributor Author

Zamiell commented Aug 17, 2023

how long do PRs usually sit after being approved but before being merged?

@fisker fisker merged commit 6d15a02 into sindresorhus:main Aug 17, 2023
21 checks passed
@cmdcolin
Copy link

random quip: it would be cool to provide "examples" of what this text means e.g. a little code snippet showing the improved type narrowing, etc. as it's a little advanced (i'm just an onlooker of this repo)

@Zamiell
Copy link
Contributor Author

Zamiell commented Aug 22, 2023

The type narrowing difference is illustrated by the following code:

declare const foo: Foo | undefined;

if (foo === undefined) {
  return;
}

for (const element of array) {
  // type of `foo` is `Foo`
}
declare const foo: Foo | undefined;

if (foo === undefined) {
  return;
}

array.forEach((element) => {
  // type of `foo` is `Foo | undefined` (because we passed a function boundary)
});

The variable mutation difference is illustrated by the following code:

function countArray(array: number[]) {
  let count = 0;

  for (const element of array) {
    count += element;
  }

  return count;
}
function countArray(array: number[]) {
  let count = 0;

  array.forEach((element) => {
    count += element;
  });

  return count; // lint error: count is never modified (because we passed a function boundary)
}

@cmdcolin
Copy link

excellent, thanks for the demo!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants