Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Last active July 6, 2023 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pesterhazy/82a4166e1f5a8dd1689f5f1f99eae79c to your computer and use it in GitHub Desktop.
Save pesterhazy/82a4166e1f5a8dd1689f5f1f99eae79c to your computer and use it in GitHub Desktop.
JS Headers iteration wat
headers = new Headers([["a","A"],["b","B"]]);
headers.forEach((_,k) => headers.delete(k));
console.log([...headers].length);
// expected: 0
// actual: 1 (Chrome 114)
// actual: 1 (Bun.js v0.6.13)
// actual: 1 (Safari 16.4)
// actual: 0 (Node v18.12.1)
@pesterhazy
Copy link
Author

Seems like a peculiarity of how browsers implement the Headers class

If you replace Headers with Map, it all works as expected

headers = new Headers([["a","A"],["b","B"]]);
headers.forEach((_,k) => headers.delete(k));
console.log([...headers].length);

// actual: 0

@pesterhazy
Copy link
Author

This doesn't work as expected:

headers = new Headers([["a","A"],["b","B"]]);
for (let k of headers.keys()) { headers.delete(k); }
console.log([...headers].length);

This does:

headers = new Headers([["a","A"],["b","B"]]);
for (let k of [...headers.keys()]) { headers.delete(k); }
console.log([...headers].length);

@smeijer
Copy link

smeijer commented Jul 6, 2023

// actual: 1 (Node v18.14.2)

@pesterhazy
Copy link
Author

See this test case in Web Platform Test (WPT) web-platform-tests/wpt@a31d3ba

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment