TheAlgorithms/JavaScript · error · Error

value should be between 0 and 1

Error message

value should be between 0 and 1

What it means

Thrown by hsvToRgb when value (brightness) is below 0 or above 1. It is the third and last range guard, reached only after hue and saturation pass. Like saturation, value is a fraction in [0,1], not a percentage.

Source

Thrown at Conversions/RgbHsvConversion.js:29

/**
 * Conversion from the HSV-representation to the RGB-representation.
 *
 * @param hue Hue of the color.
 * @param saturation Saturation of the color.
 * @param value Brightness-value of the color.
 * @return The tuple of RGB-components.
 */
export function hsvToRgb(hue, saturation, value) {
  if (hue < 0 || hue > 360) {
    throw new Error('hue should be between 0 and 360')
  }

  if (saturation < 0 || saturation > 1) {
    throw new Error('saturation should be between 0 and 1')
  }

  if (value < 0 || value > 1) {
    throw new Error('value should be between 0 and 1')
  }

  const chroma = value * saturation
  const hueSection = hue / 60
  const secondLargestComponent = chroma * (1 - Math.abs((hueSection % 2) - 1))
  const matchValue = value - chroma

  return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent)
}

/**
 * Conversion from the RGB-representation to the HSV-representation.
 *
 * @param red Red-component of the color.
 * @param green Green-component of the color.
 * @param blue Blue-component of the color.
 * @return The tuple of HSV-components.
 */

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Convert percentages to fractions: value / 100.
  2. Clamp: Math.max(0, Math.min(1, value)).
  3. Validate Number.isFinite(value) && value >= 0 && value <= 1 before calling.

Example fix

// before
hsvToRgb(180, 0.5, 120)
// after
hsvToRgb(180, 0.5, Math.min(1, 120 / 100))
Defensive patterns

Strategy: validation

Validate before calling

if (!Number.isFinite(value) || value < 0 || value > 1) {
  throw new Error('value must be a fraction in [0,1]')
}
hsvToRgb(hue, saturation, value)

Type guard

const isValidFraction = (x) => Number.isFinite(x) && x >= 0 && x <= 1

Try / catch

try {
  hsvToRgb(hue, saturation, value)
} catch (e) {
  if (/value should be between/.test(e.message)) {
    return hsvToRgb(hue, saturation, Math.max(0, Math.min(1, value)))
  }
  throw e
}

Prevention

When it happens

Trigger: Calling hsvToRgb(180, 0.5, 1.2), hsvToRgb(180, 0.5, -0.1), or hsvToRgb(180, 0.5, 80) where 80 is a percentage passed as a fraction.

Common situations: Brightness as a percentage (0-100) from a UI control; values above 1 from gamma/blend math; negative values from a subtractive adjustment.

Related errors


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