The reading room
JavaScript guides.
Small, reproducible recipes for arrays, objects, strings, asynchronous work, and common language mistakes.
45 guides · Examples, explanations, and practical limits.
In this topic
45 articles
Remove duplicate values from a JavaScript array
Wrap an array in a Set and spread it into a new array to remove repeated primitive values while keeping the order of their first appearance.
Deduplicate objects by ID with a JavaScript Map
Use a Map keyed by a stable identifier to keep one record per ID. Reassigning an existing key replaces its value without moving that key to a new insertion position.
Sort numbers correctly in JavaScript
Pass a numeric comparator to Array.sort. Without one, JavaScript compares string representations, so 10 can appear before 2. Copy the array first when callers need…
Sort an array without changing the original
Use toSorted to return a sorted copy of an array. It expresses the nonmutating operation directly and is useful when several parts of a program share the same array.
Sort human-readable text with Intl.Collator
Use Intl.Collator when sorting names or filenames for people. A chosen locale and options make the intended text ordering clearer than relying on Unicode code-point…
Remove null and undefined without dropping zero
Use an explicit nullish predicate when filtering values. Boolean filtering also removes zero, false, and empty strings, which may be legitimate data rather than…
Find one object by property in an array
Use Array.find when you want the first record matching a condition. It returns the record itself, or undefined if no element matches; it does not return an array of…
Choose between Array.some and Array.every
Use some to ask whether at least one entry passes a test, and every to ask whether all entries pass. Both stop once their answer is determined.
Flatten one level of nested arrays
Call flat with depth 1 to combine one level of nested arrays into a new array. Deeper arrays remain nested, which helps preserve meaningful grouping further down the…
Map and flatten records with flatMap
Use flatMap when one input entry should produce zero, one, or several output entries. Return an empty array to omit an entry and a short array to expand it.
Sum values with reduce and an initial value
Supply an initial accumulator when using reduce to sum values. An initial zero makes the empty-array result well defined and keeps the accumulator type predictable.
Copy an object with spread syntax
Object spread creates a new object from another object’s enumerable own properties. It is useful for changing a few top-level fields while retaining the remaining values.
Deep-clone supported data with structuredClone
Use structuredClone to copy supported structured data, including nested objects and cyclic references. It is a better fit than JSON round-tripping when you need…
Read optional nested values safely
Optional chaining stops a property access when the value immediately to its left is null or undefined. It helps read partially populated records without nested…
Use nullish coalescing for defaults
Use the nullish coalescing operator when a default should apply only to null or undefined. Unlike logical OR, it preserves intentional values such as zero, false, and…
Transform object values with entries and fromEntries
Convert an object into entries, transform the key-value pairs, then rebuild it with Object.fromEntries. This is useful for explicit transformations of a flat…
Check whether an object owns a property
Use Object.hasOwn to distinguish a property stored directly on an object from one inherited through its prototype. It also works when the object has no prototype.
Group records with Object.groupBy
Object.groupBy collects iterable values into arrays under keys returned by a callback. Use it when a report needs one group per status or another simple category.
Destructure object properties with defaults
Destructuring can name local variables and supply defaults for undefined properties. Use it to make a small set of expected options visible at the start of a function.
Validate an integer string before converting it
For a complete integer field, validate the whole string and then check Number.isSafeInteger. ParseInt alone accepts a valid numeric prefix and can hide trailing…
Check for NaN without coercion
Use Number.isNaN when you want to know whether a value is specifically the numeric NaN value. It does not coerce arbitrary strings or objects into numbers first.
Format decimal numbers for display
Use toFixed when you need a fixed number of decimal places in display text. It returns a string and should not be mistaken for a change to the precision of the stored…
Format currency with Intl.NumberFormat
Use Intl.NumberFormat with an explicit locale and currency to display monetary amounts. The formatter chooses currency symbols, separators, and default fraction…
Trim whitespace from the edges of a string
Use trim to remove leading and trailing whitespace while preserving whitespace inside a string. This is a common first step for text input, but it should follow the…
Replace every literal substring
Use replaceAll with a string search value when every literal occurrence should be replaced. It avoids constructing a regular expression for input that is meant to be…
Split a small text string into lines
For a small in-memory text value, split on a line-ending expression that recognizes CRLF, LF, and CR. Keep or remove a trailing empty line according to the file…
Normalize Unicode text before comparison
Normalize strings to a chosen Unicode normalization form before comparing visually equivalent text. NFC combines supported character sequences into their canonical…
Count grapheme clusters in a string
Use Intl.Segmenter with grapheme granularity when counting user-perceived text units. String.length counts UTF-16 code units, which can split emoji and…
Escape a literal value for a regular expression
Use RegExp.escape when a dynamic string must be matched literally inside a regular expression. It protects punctuation from becoming pattern syntax and handles edge…
Convert a valid Date to an ISO timestamp
Use toISOString to serialize a valid Date as a UTC timestamp. Check that the date is valid first when the value comes from an external source.
Display a date in an explicit time zone
Use Intl.DateTimeFormat with a timeZone option when a timestamp should be shown in a particular region. Otherwise the environment’s default zone can change the…
Compare two timestamps by their numeric time
Compare Date.getTime values when checking the order of actual instants. The numeric result is milliseconds since the epoch, independent of how the date is displayed.
Run independent asynchronous tasks with Promise.all
Use Promise.all to await independent tasks together and receive results in input order. It rejects when an input promise rejects, even if other tasks are still running.
Collect successes and failures with Promise.allSettled
Use Promise.allSettled when every task outcome matters, including failures. It waits for all inputs and returns a status record for each one in input order.
Await work sequentially with for...of
Use a for...of loop with await when tasks must complete one at a time. An async callback passed to forEach does not make the surrounding function wait for those…
Limit concurrent asynchronous jobs
Use a small worker pool when a list of asynchronous jobs should run concurrently without starting every job at once. Each worker takes the next available index and…
Clean up asynchronous work with finally
Use finally for cleanup that must run after an awaited operation succeeds or fails. Keep the original error visible by avoiding a return or replacement error inside…
Create an application-specific Error subclass
Subclass Error when callers need to distinguish a known application failure from unrelated exceptions. Give it a meaningful name and retain a useful message for logs…
Yield array batches with a generator
Use a generator to yield slices of an array a batch at a time. Consumers can process one batch before requesting the next instead of first constructing an array…
Check array membership with includes
Use Array.includes when you need a boolean answer about whether an array contains a value. It is clearer than comparing an index against minus one when the index…
Preserve ties when sorting records
Return zero from a comparator when two records have equal sort keys. Stable sorting preserves their previous relative order, allowing a deliberate tie rule without…
Serialize BigInt values deliberately
Convert BigInt values to decimal strings before JSON serialization. JSON.stringify does not serialize BigInt directly, and converting a large integer to Number can…
Understand what Object.freeze protects
Object.freeze prevents changes to an object’s own properties, but it does not recursively freeze nested objects. Treat it as a shallow integrity constraint rather…
Generate a casual random integer in a range
For a non-security task, use Math.random with a half-open integer range: minimum inclusive, maximum exclusive. Naming both boundaries helps avoid off-by-one errors in…
Use default function parameters predictably
Default parameters apply when an argument is omitted or explicitly undefined. They do not replace null, false, zero, or an empty string.
No matching articles. Try another title or topic.