How Lodash toFinite Coerces Strings
In JavaScript development, converting messy string input into
reliable numeric data is a common requirement. The Lodash
_.toFinite method coerces strings into finite
floating-point or integer numbers by passing the input through an
internal parsing pipeline, safely falling back to zero for non-numeric
values, and clamping extreme values within the safe bounds of
Number.MAX_VALUE.
The Coercion Pipeline
When a string is passed to _.toFinite(value), Lodash
processes it in sequential stages:
- Whitespace Trimming: Leading and trailing whitespace characters are stripped from the string.
- Numeric Parsing: The string is parsed using
Lodash’s internal
toNumberutility.- Standard integer and floating-point representations (e.g.,
"42","3.14","-10.5") are converted to standard JavaScript numbers. - Scientific notation strings (e.g.,
"1e5") are evaluated properly. - Radix prefixes are detected and parsed: binary
(
"0b101"), octal ("0o77"), and hexadecimal ("0x1a"). Bad signed hex strings (e.g.,"-0x1a") are parsed asNaN.
- Standard integer and floating-point representations (e.g.,
- Handling Non-Numeric and Invalid Strings: In native
JavaScript,
Number("invalid")returnsNaN. However,_.toFinitechecks whether the parsed result isNaN. If a string cannot be resolved into a valid number (such as"hello","12px", or empty strings""),_.toFinitecoerces the result to0. - Infinity Clamping: If the string explicitly
represents an infinite value, such as
"Infinity"or"-Infinity", it does not remain infinite. Lodash clamps positive infinity toNumber.MAX_VALUE(1.7976931348623157e+308) and negative infinity to-Number.MAX_VALUE(-1.7976931348623157e+308).
Coercion Behavior Summary
_.toFinite("3.2")yields3.2_.toFinite(" 42 ")yields42_.toFinite("0b10")yields2_.toFinite("0x1f")yields31_.toFinite("")yields0_.toFinite("abc")yields0_.toFinite("100px")yields0_.toFinite("Infinity")yields1.7976931348623157e+308_.toFinite("-Infinity")yields-1.7976931348623157e+308
Through this coercion sequence, _.toFinite guarantees
that any string input is transformed into a valid, safe, and finite
numeric type without throwing runtime errors or returning
NaN.