The snippet library.
Small, practical examples. Search by task or narrow things down below.
Detect an invalid Date object
JavaScript: An invalid Date has a NaN time value.
JavaScript✓ Tested
Detect NaN without converting the input
JavaScript: Number.isNaN tests the special numeric value instead of applying string-to-number conversion.
JavaScript✓ Tested
Display a number with a fixed decimal width
JavaScript: toFixed returns a formatted string rather than a numeric value.
JavaScript✓ Tested
Distinguish an own property from an inherited one
JavaScript: Object.hasOwn avoids depending on an object’s possibly shadowed hasOwnProperty method.
JavaScript✓ Tested
Divide using a fractional number
JavaScript: Use a floating-point operand to preserve the fractional part of a division.
JavaScript✓ Tested
Drop the fractional part toward zero
JavaScript: Math.trunc differs from floor for negative inputs.
JavaScript✓ Tested
Explain a calculation with a comment
JavaScript: Keep the code executable while documenting why a fixed input is used.
JavaScript✓ Tested
Extract all regex matches with their groups
JavaScript: matchAll requires a global regular expression and returns an iterator of matches.
JavaScript✓ Tested
Extract text by start and end positions
JavaScript: String slice uses an inclusive start and exclusive end measured in UTF-16 code units.
JavaScript✓ Tested
Extract the text after the last delimiter
JavaScript: Use lastIndexOf when earlier occurrences should remain part of the prefix.
JavaScript✓ Tested
Filter even numbers
Create a JavaScript array containing only even values.
JavaScript✓ Tested
Find members absent from another set
JavaScript: Negate a membership test to calculate the set difference.
JavaScript✓ Tested