Lodash _.toLength() method
What you’ll learn
- What ECMAScript’s
ToLengthabstract op does, and how_.toLengthmirrors it. - Why the output is always in
[0, 2³² − 1]. - How
_.toLengthchains on top of_.toInteger. - When to reach for it instead of
_.toIntegeror a manual clamp.
Prerequisites
You’ve finished the _.toInteger tutorial; _.toLength is a clamp on top of it.
- You know that JavaScript arrays have a hard cap at
2³² − 1elements. - Try-it labs load lodash from the CDN.
Overview
The one-line implementation: return value ? _.clamp(_.toInteger(value), 0, 2³² − 1) : 0. The output is guaranteed to be a safe Array length you can hand to new Array(n) or use as an upper bound for an indexed loop.
Always non-negative
Negatives, NaN, falsy → 0.
Hard upper limit
Anything ≥ 2³² clamps to 2³² − 1 = 4 294 967 295.
Spec-compliant
Mirrors the ECMAScript ToLength abstract operation used by Array.prototype.*.
Syntax
_.toLength(value) - value: the value to convert.
- Returns: a non-negative integer in
[0, 2³² − 1]. Always safe as an array length.
Lodash docs baseline
Four cases pulled straight from the official docs.
import toLength from "lodash/toLength";
console.log(
"3.2: " + toLength(3.2) + "\n" + // 3
"MIN_VALUE: " + toLength(Number.MIN_VALUE) + "\n" + // 0
"Infinity: " + toLength(Infinity) + "\n" + // 4294967295 (2^32 - 1)
"'3.2' string: " + toLength("3.2") // 3
); Clamp behavior: negatives & the upper limit
Negatives collapse to 0; values beyond 2³² − 1 clamp down. Compare with _.toInteger to see the difference.
import toLength from "lodash/toLength";
import toInteger from "lodash/toInteger";
console.log(
"toLength(-5): " + toLength(-5) + "\n" + // 0 (clamped)
"toInteger(-5): " + toInteger(-5) + "\n" + // -5 (no clamp)
"toLength(4294967296): " + toLength(4294967296) + "\n" + // 4294967295
"toLength(5e9): " + toLength(5e9) + "\n" + // 4294967295
"toLength(-Infinity): " + toLength(-Infinity) // 0
); Safe new Array(n) sizing
A practical use: anywhere you preallocate an array from untrusted input, _.toLength guarantees the call won’t throw “Invalid array length”.
import toLength from "lodash/toLength";
function makeBuffer(requested) {
const size = toLength(requested);
return new Array(size);
}
console.log("'42': len=" + makeBuffer("42").length); // 42
console.log("-5: len=" + makeBuffer(-5).length); // 0
console.log("'abc': len=" + makeBuffer("abc").length); // 0
console.log("9e99: len=" + makeBuffer(9e99).length); // 4294967295
console.log("null: len=" + makeBuffer(null).length); // 0
try {
new Array(4294967296);
} catch (err) {
console.log("raw new Array(2^32):", err.message); // RangeError
} 📋 _.toLength vs related conversions
| Input | _.toLength | _.toInteger | _.toFinite |
|---|---|---|---|
3.7 | 3 | 3 | 3.7 |
-5 | 0 | -5 | -5 |
NaN | 0 | 0 | 0 |
Infinity | 4294967295 | 1.79e+308 | 1.79e+308 |
1e15 | 4294967295 | 1e15 | 1e15 |
Pitfalls to avoid
Negatives become 0
_.toLength(-5) is 0, no error. If you need to distinguish “invalid” from “empty”, validate before calling.
Silent clamp at 2³² − 1
Huge inputs lose precision invisibly. If you’re working with counts larger than 4 294 967 295, store them outside of an Array.
BigInt throws
_.toLength(1n) raises “Cannot convert a BigInt value to a number.” Convert with Number(bigint) first if you can accept precision loss.
❓ FAQ
Summary
- Purpose: coerce anything into a legal Array length—non-negative, ≤
2³² − 1. - Remember: built on top of
_.toInteger, then clamped. Negatives andNaNbecome0;Infinitybecomes4 294 967 295. - Next: head to Lodash _.toNumber() —
_.toNumberis the underlying number-parsing primitive.
_.toLength’s upper bound is 2³² − 1 = 4 294 967 295—the exact maximum length a JavaScript array can hold. Try new Array(4294967296) in any engine and you’ll get “Invalid array length”; lodash clamps to the highest legal value instead.
5 people found this page helpful
