TheAlgorithms/JavaScript · error · Error

blue should be between 0 and 255

Error message

blue should be between 0 and 255

What it means

Thrown by rgbToHsv when blue is below 0 or above 255. It is the third and last per-channel guard, reached only after red and green pass. Same 8-bit integer range contract.

Source

Thrown at Conversions/RgbHsvConversion.js:58

/**
 * 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.
 */
export function rgbToHsv(red, green, blue) {
  if (red < 0 || red > 255) {
    throw new Error('red should be between 0 and 255')
  }

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

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

  const dRed = red / 255
  const dGreen = green / 255
  const dBlue = blue / 255
  const value = Math.max(Math.max(dRed, dGreen), dBlue)
  const chroma = value - Math.min(Math.min(dRed, dGreen), dBlue)
  const saturation = value === 0 ? 0 : chroma / value
  let hue

  if (chroma === 0) {
    hue = 0
  } else if (value === dRed) {
    hue = 60 * ((dGreen - dBlue) / chroma)
  } else if (value === dGreen) {
    hue = 60 * (2 + (dBlue - dRed) / chroma)
  } else {
    hue = 60 * (4 + (dRed - dGreen) / chroma)

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Clamp and round: Math.max(0, Math.min(255, Math.round(blue))).
  2. Validate Number.isFinite(blue) && blue >= 0 && blue <= 255 before calling.
  3. Clamp all channels uniformly with a shared helper.

Example fix

// before
rgbToHsv(0, 0, 300)
// after
const clamp8 = (c) => Math.max(0, Math.min(255, Math.round(c)))
rgbToHsv(0, 0, clamp8(300))
Defensive patterns

Strategy: validation

Validate before calling

if (!Number.isFinite(blue) || blue < 0 || blue > 255) {
  throw new Error('blue must be an integer in [0,255]')
}
rgbToHsv(red, green, blue)

Type guard

const isChannel8 = (c) => Number.isFinite(c) && c >= 0 && c <= 255

Try / catch

try {
  rgbToHsv(red, green, blue)
} catch (e) {
  if (/blue should be between/.test(e.message)) {
    return rgbToHsv(red, green, Math.max(0, Math.min(255, Math.round(blue))))
  }
  throw e
}

Prevention

When it happens

Trigger: Calling rgbToHsv(0, 0, 300), rgbToHsv(0, 0, -2), or rgbToHsv(0, 0, 256).

Common situations: Blue channel overflow/underflow from color math; float rounding up; negative values from a difference; 16-bit source not rescaled to 8-bit.

Related errors


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