1. Separate product sorting from object key order
ECMAScript OwnPropertyKeys iterates non-negative integer index keys in ascending numeric order before string keys in insertion order. Using a plain object to deduplicate or store timestamped buckets can reorder negative or string keys unexpectedly.
When an API promises chronological or insertion order, use a Map or sort explicitly with a numeric comparator instead of relying on plain-object key iteration.
2. Match String.length to the real counting unit
In JavaScript, String.prototype.length and slice() operate on 16-bit UTF-16 code units, not Unicode scalar values or grapheme clusters. Truncating a user name at index 10 can slice an emoji in half and produce an invalid surrogate.
Use Array.from(text) or Intl.Segmenter when the product contract counts characters or graphemes, and keep validation and truncation on the same unit.
const name = "Ada🚀";
console.log(name.length); // 5 UTF-16 code units
console.log(Array.from(name).length); // 4 Unicode scalar values3. Reserve async capacity before awaiting
In concurrent pumps and work queues, checking activeWorkers < limit after an await creates a window where multiple iterations pass the check before any increments the counter. Similarly, observing a cold async iterable before passing it on can consume the stream.
Reserve capacity synchronously before yielding at await, normalize or tee shared async sources once, and release slots in a finally block so errors never leak concurrency budget.
- Reserve concurrency slots synchronously before any await.
- Normalize cold vs hot async sources once before sharing.
- Guard recursive object merges with Object.hasOwn and null-prototype objects.
Frequently asked questions
- Why does Object.keys reorder numeric keys in JavaScript?
- The ECMAScript specification requires OwnPropertyKeys to return array-index keys ("0", "1", "2") in ascending numeric order first, followed by remaining string keys in insertion order. Use a Map when insertion order must hold for all keys.
- How do you prevent prototype pollution when merging JavaScript objects?
- Check Object.hasOwn(source, key), skip __proto__, constructor, and prototype keys, and avoid mutating inherited properties on target objects.
Further reading
Start with primary reports and documentation. Community discussions are discovery leads, not evidence on their own.