TheAlgorithms/JavaScript · error · TypeError

Argument not an Integer

Error message

Argument not an Integer

What it means

BinaryCountSetBits counts set bits via Brian Kernighan's algorithm (a &= a - 1). Non-integer numbers like 21.1 have non-terminating binary expansions, which would loop infinitely counting 1-bits, so the function rejects anything that fails Number.isInteger.

Source

Thrown at Bit-Manipulation/BinaryCountSetBits.js:15

/*
    author: vivek9patel
    license: GPL-3.0 or later

    This script will find number of 1's
    in binary representation of given number

*/

function BinaryCountSetBits(a) {
  'use strict'

  // check whether input is an integer, some non-integer number like, 21.1 have non-terminating binary expansions and hence their binary expansion will contain infinite ones, thus the handling of non-integers (including strings,objects etc. as it is meaningless) has been omitted

  if (!Number.isInteger(a)) throw new TypeError('Argument not an Integer')

  let count = 0
  while (a) {
    a &= a - 1
    count++
  }

  return count
}

export { BinaryCountSetBits }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a plain integer, e.g. BinaryCountSetBits(13).
  2. Coerce strings/fractions explicitly first: BinaryCountSetBits(Math.trunc(Number(input))).
  3. Guard with Number.isInteger(x) before calling if the source is untrusted.

Example fix

// before
BinaryCountSetBits(formData.age) // string from input
// after
const n = Math.trunc(Number(formData.age))
if (Number.isInteger(n)) BinaryCountSetBits(n)
Defensive patterns

Strategy: type-guard

Validate before calling

function countBitsSafe(x) {
  const n = Math.trunc(Number(x));
  if (!Number.isInteger(n)) throw new TypeError('Argument not an Integer');
  return BinaryCountSetBits(n);
}

Type guard

/** @param {unknown} x @returns {x is number} */
const isInt = x => typeof x === 'number' && Number.isInteger(x);

Try / catch

try { return BinaryCountSetBits(value); }
catch (e) {
  if (e instanceof TypeError && /not an Integer/.test(e.message)) {
    return BinaryCountSetBits(Math.trunc(Number(value)));
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing a float (21.1), a numeric string ("5"), NaN, Infinity, undefined, null, or any non-number. Note: negative integers work but loop on two's-complement bits.

Common situations: Receiving input from a form/input element (always a string), a parseFloat result, or a division that yielded a fraction.

Related errors


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