TheAlgorithms/JavaScript · error · Error

green should be between 0 and 255

Error message

green should be between 0 and 255

What it means

Thrown by rgbToHsv when green is below 0 or above 255. It is the second per-channel guard, reached only after red passes. Same 8-bit integer range contract as the red channel.

Source

Thrown at Conversions/RgbHsvConversion.js:54

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

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Clamp and round: Math.max(0, Math.min(255, Math.round(green))).
  2. Validate Number.isFinite(green) && green >= 0 && green <= 255 before calling.
  3. Apply the same clamp to all three channels in one helper.

Example fix

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

Strategy: validation

Validate before calling

if (!Number.isFinite(green) || green < 0 || green > 255) {
  throw new Error('green 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 (/green should be between/.test(e.message)) {
    return rgbToHsv(red, Math.max(0, Math.min(255, Math.round(green))), blue)
  }
  throw e
}

Prevention

When it happens

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

Common situations: Green channel overflow from a blend or filter; float rounding to 256; negative from subtractive logic; unresolved 16-bit input.

Related errors


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