TheAlgorithms/JavaScript · error · TypeError

The value of latitude or longitude should be a number

Error message

The value of latitude or longitude should be a number

What it means

Thrown by the internal `validateLatOrLong(value)` helper used inside `haversineDistance` when a latitude or longitude argument is not `typeof === 'number'`. The guard runs per coordinate, so the offending value is whichever one was passed in. NaN passes this check (it is typeof 'number') and produces a NaN distance.

Source

Thrown at Navigation/Haversine.js:40

  const pi = Math.PI
  const cos1 = (latitude1 * pi) / 180.0
  const cos2 = (latitude2 * pi) / 180.0
  const deltaLatitude = ((latitude2 - latitude1) * pi) / 180.0
  const deltaLongitude = ((longitude2 - longitude1) * pi) / 180.0

  const alpha =
    Math.sin(deltaLatitude / 2) * Math.sin(deltaLatitude / 2) +
    Math.cos(cos1) *
      Math.cos(cos2) *
      Math.sin(deltaLongitude / 2) *
      Math.sin(deltaLongitude / 2)
  const constant = 2 * Math.atan2(Math.sqrt(alpha), Math.sqrt(1 - alpha))
  return earthRadius * constant
}

const validateLatOrLong = (value) => {
  if (typeof value !== 'number') {
    throw new TypeError('The value of latitude or longitude should be a number')
  }
}

export { haversineDistance }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce each coordinate with `Number(...)` and verify `Number.isFinite` before calling.
  2. Reject out-of-range latitudes (>90, <-90) and longitudes (>180, <-180) upstream.
  3. When the source is JSON, schema-validate the coordinate fields.

Example fix

// before
haversineDistance(a.lat, a.lon, b.lat, b.lon) // a.lat could be '48.85'

// after
const lat1 = Number(a.lat), lon1 = Number(a.lon), lat2 = Number(b.lat), lon2 = Number(b.lon)
if (![lat1, lon1, lat2, lon2].every(Number.isFinite)) throw new TypeError('all coords must be numbers')
haversineDistance(lat1, lon1, lat2, lon2)
Defensive patterns

Strategy: type-guard

Validate before calling

const coords = [lat1, lon1, lat2, lon2].map(Number)
if (!coords.every((c) => typeof c === 'number' && Number.isFinite(c))) {
  throw new TypeError('all coordinates must be finite numbers')
}
haversineDistance(...coords)

Type guard

const isCoordinate = (x) => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) <= 180

Prevention

When it happens

Trigger: Call `haversineDistance(lat, lon, lat2, lon2)` where any of the four is a string, null, undefined, or object. Common when geocoordinates come from JSON where they were serialised as strings.

Common situations: GeoJSON or REST API responses with numeric fields as strings, browser Geolocation `coords.latitude` mis-forwarded, or empty form fields passed unchanged.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/4258380497f3c403. Report an issue: GitHub.