Lodash Number methods

Beginner
⏱️ 7 min read
📚 Updated: May 2026
🎯 2 Code examples
Lodash

What you’ll learn

  • The three helpers in the Number category and when each one saves you from hand-rolled bounds logic.
  • How _.inRange differs from >= / <= chains (half-open interval and argument normalization).
  • How _.random chooses integer versus floating output and why it is still not cryptographic.
  • How to import Lodash per method in modern bundlers.
  • Where to open each _.methodName tutorial 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 with NaN and infinities.
  • Half-open ranges: intervals written [start, end) include start but exclude end — the model behind _.inRange.
  • Math.random: returns a float in [0, 1); Lodash builds integer and bounded-float helpers on top.
  • Modules: import from lodash/methodName in bundlers or require('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.

SituationHand-rolledConsider Lodash
Clamp a slider valueMath.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-1n >= 0 && n < len_.inRange(n, len) — remember the exclusive end
Random array indexMath.floor(Math.random() * arr.length)_.random(arr.length - 1) when bounds are inclusive integers
Secrets or fairness-critical drawsCryptographic APIsDo not use _.random; it wraps Math.random
1

Install and import

Install lodash once per project, then import only the number helpers you call.

Terminal
npm install lodash
javascript
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
2

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).

javascript
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.

  1. Clamp first: clamp — master bound ordering before combining with sliders or canvas math.
  2. Ranges second: inRange — internalize the exclusive upper edge.
  3. Random last: random — learn integer versus floating overloads and the crypto caveat.

💻 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/lodash for 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.

MethodWhat 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

Exclusive end

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.

Security

Predictable randomness

_.random is fine for games and fixtures, not session tokens. Reach for platform CSPRNGs.

NaN

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

Three helpers: clamp pins a value inside bounds, inRange tests membership on a half-open numeric interval, and random generates bounded integers or floats without writing boilerplate around Math.random.
It normalizes argument order when start exceeds end, defaults start to 0 when you pass only an upper bound, and documents the exclusive end so you do not accidentally include the last index of a slice-style range.
No. It uses Math.random under the hood, which is not cryptographically secure. Use crypto.getRandomValues in browsers or crypto.randomBytes in Node.js for tokens, keys, or nonces.
Same as other Lodash modules: import clamp from "lodash/clamp" (and similar) so bundlers can tree-shake unused code.

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.
Did you know?

_.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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful