TheAlgorithms/JavaScript · error · Error

Invalid arguments

Error message

Invalid arguments

What it means

Thrown by quickSelectSearch() when array is falsy or when k is greater than or equal to the array length. The algorithm places the k-th smallest element at its sorted index, so a valid k must be in [0, array.length-1]; k outside that range has no defined result. The guard also rejects null/undefined arrays since they have no length property.

Source

Thrown at Search/QuickSelectSearch.js:16

/*
 * Places the `k` smallest elements in `array` in the first `k` indices: `[0..k-1]`
 * Modifies the passed in array *in place*
 * Returns a slice of the wanted elements for convenience
 * Efficient mainly because it never performs a full sort.
 *
 * The only guarantees are that:
 *
 * - The `k`th element is in its final sort index (if the array were to be sorted)
 * - All elements before index `k` are smaller than the `k`th element
 *
 * [Reference](http://en.wikipedia.org/wiki/Quickselect)
 */
export function quickSelectSearch(array, k) {
  if (!array || array.length <= k) {
    throw new Error('Invalid arguments')
  }

  let from = 0
  let to = array.length - 1
  while (from < to) {
    let left = from
    let right = to
    const pivot = array[Math.ceil((left + right) * 0.5)]

    while (left < right) {
      if (array[left] >= pivot) {
        const tmp = array[left]
        array[left] = array[right]
        array[right] = tmp
        --right
      } else {
        ++left
      }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Ensure 0 <= k < array.length: clamp k to array.length - 1.
  2. Handle the empty-array case explicitly before calling.
  3. When asking for the top-k smallest, remember the function returns a slice, so pass k as the count minus one for the pivot index.

Example fix

// before
const res = quickSelectSearch(arr, arr.length)

// after
const k = Math.min(arr.length - 1, Math.max(0, desiredK))
const res = quickSelectSearch(arr, k)
Defensive patterns

Strategy: validation

Validate before calling

function safeQuickSelectSearch(array, k) {
  if (!Array.isArray(array) || array.length === 0) {
    throw new Error('array must be a non-empty array')
  }
  if (!Number.isInteger(k) || k < 0 || k >= array.length) {
    throw new RangeError(`k must be in [0, ${array.length - 1}]`)
  }
  return quickSelectSearch(array, k)
}

Type guard

function isValidK(array, k) {
  return Array.isArray(array) && array.length > 0 && Number.isInteger(k) && k >= 0 && k < array.length
}

Try / catch

try {
  quickSelectSearch(arr, k)
} catch (e) {
  if (e.message === 'Invalid arguments') {
    return quickSelectSearch(arr, Math.min(k, arr.length - 1))
  }
  throw e
}

Prevention

When it happens

Trigger: Calling quickSelectSearch([1,2,3], 3) (k equals length), quickSelectSearch([1,2,3], 5) (k exceeds length), quickSelectSearch(null, 0), or quickSelectSearch([], 0) with k=0 against an empty array (0 <= 0 triggers it).

Common situations: Computing k from array.length without subtracting for 0-indexing (e.g. k = arr.length); passing a percentile-derived k that rounds up to length; empty array from a filtered result with k=0.

Related errors


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