Lodash Number methods
What you’ll learn
- The three helpers in the Number category and when each one saves you from hand-rolled bounds logic.
- How
_.inRangediffers from>=/<=chains (half-open interval and argument normalization). - How
_.randomchooses integer versus floating output and why it is still not cryptographic. - How to import Lodash per method in modern bundlers.
- Where to open each
_.methodNametutorial on CodeToFun as those pages are added.
Prerequisites
Basic JavaScript numbers, comparisons, and modules. Pair with Lodash Math methods when you need rounding or aggregation after clamping.
- Numeric comparisons: how
<,<=, and chained checks behave withNaNand infinities. - Half-open ranges: intervals written
[start, end)includestartbut excludeend— the model behind_.inRange. Math.random: returns a float in[0, 1); Lodash builds integer and bounded-float helpers on top.- Modules:
importfromlodash/methodNamein bundlers orrequire('lodash/methodName')in Node.js.
Key concepts
The Number category is intentionally tiny. Each function answers one UI or game-loop style question without pulling in collection helpers.
Bounds & clamp
_.clamp(n, lower, upper) pins values when lower <= upper; if min/max might be flipped, order them before calling (lodash does not swap).
Half-open test
_.inRange(n, start, end) mirrors slice-style ranges: inclusive low, exclusive high, with optional start defaulting to 0.
Bounded randomness
_.random picks inclusive integer endpoints by default, or floats when you pass true as the floating flag in the documented overloads.
Overview
Use clamp after user input or physics integration, inRange for hit-testing numeric intervals, and random for dice rolls, jitter, or mock data — never for secrets.
Safety rails
Sliders, zoom levels, and pagination indices stay inside min/max without repeating Math.min(Math.max(...)) everywhere.
Interval checks
Compare timestamps, scores, or normalized device coordinates against configurable windows with one call.
Procedural noise
Integer overloads are ideal for array indexes and loot tables; floating overloads add non-grid jitter.
⚖️ Lodash vs hand-rolled helpers
These three functions are small enough to rewrite inline. Lodash still wins when you want tested edge cases (normalized inRange endpoints, default start) and identical behavior in Node and the browser.
| Situation | Hand-rolled | Consider Lodash |
|---|---|---|
| Clamp a slider value | Math.min(max, Math.max(min, n)) | _.clamp(n, min, max) after you order min/max (lodash does not swap reversed bounds) |
Test index inside 0 .. length-1 | n >= 0 && n < len | _.inRange(n, len) — remember the exclusive end |
| Random array index | Math.floor(Math.random() * arr.length) | _.random(arr.length - 1) when bounds are inclusive integers |
| Secrets or fairness-critical draws | Cryptographic APIs | Do not use _.random; it wraps Math.random |
Install and import
Install lodash once per project, then import only the number helpers you call.
npm install lodash import clamp from "lodash/clamp";
import inRange from "lodash/inRange";
import random from "lodash/random";
const volume = clamp(150, 0, 100); // 100
const ok = inRange(3, 0, 10); // true (0 <= 3 < 10)
const roll = random(1, 6); // integer 1..6 inclusive Intervals and random shapes
_.inRange treats the upper bound as exclusive. _.random defaults to inclusive integers when you pass two numeric bounds; pass true as the floating flag for fractional results (see the per-method pages for edge cases).
import inRange from "lodash/inRange";
import random from "lodash/random";
inRange(5, 5, 10); // true (5 is included)
inRange(10, 5, 10); // false (10 is excluded)
random(5, 10); // integer in [5, 10]
random(5, 10, true); // float in [5, 10] (legacy floating flag)
random(); // 0 or 1 Suggested learning path
Walk these in order; each API fits on a sticky note but the details matter in code review.
💻 Environment and versions
- Lodash 4.x: the three methods listed here match the stable 4.x “Number” section in the official docs.
- Node.js and browsers: same package everywhere; prefer ESM imports in bundlers.
- TypeScript: install
@types/lodashfor accurate typings on per-method imports.
Method index
Each row links to a focused tutorial when it exists on this site. URLs are kebab-cased under /lodash/number/—for example /lodash/number/clamp and /lodash/number/in-range.
| Method | What it does |
|---|---|
_.clamp() | Constrain a number between a lower and upper bound (expects lower <= upper; order with Math.min/Math.max if unsure). |
_.inRange() | Return true when the number lies in the half-open interval [start, end); start defaults to 0. |
_.random() | Produce a random integer or floating value between bounds; omit args for 0 or 1. |
Pitfalls to avoid
Off-by-one with inRange
The upper bound is not included. Testing against inclusive UI labels may need end + 1 or a plain <= check instead.
Predictable randomness
_.random is fine for games and fixtures, not session tokens. Reach for platform CSPRNGs.
Garbage in, garbage out
_.clamp can yield NaN when the value never coerces to a finite number; _.inRange yields false instead. Pair with _.toNumber() or validation when data comes from forms.
❓ FAQ
Summary
- Scope: three helpers for bounds, interval membership, and bounded random values.
- Imports: per-method packages keep bundles small.
- Next step: open Lodash _.clamp() or pick any row from the index table above.
_.inRange uses a half-open interval: the lower bound is inclusive, the upper bound is exclusive — the same convention as Array.prototype.slice(start, end) and many other range APIs.
6 people found this page helpful
