6

i want to check if a number is a BigInt in a acceptable size if statement

i know there is the solution

function isBigInt(x) {
    try {
        return BigInt(x) === x; // dont use == because 7 == 7n but 7 !== 7n
    } catch(error) {
        return false; // conversion to BigInt failed, surely it is not a BigInt
    }
}

but i wanted to implement the test directly in my if statement, not in my function
can someone help me with that?

4 Answers4

6

You can use typeof. If the number is a BigInt, the typeof would be "bigint". Otherwise, it will be "number"

var numbers = [7, BigInt(7), "seven"];
numbers.forEach(num => {
  if (typeof num === "bigint") {
    console.log("It's a BigInt!");
  } else if (typeof num === "number") {
    console.log("It's a number!");
  } else {
    console.log("It's not a number or a BigInt!");
  }
});
Rojo
  • 2,749
  • 1
  • 13
  • 34
  • A bigint can also be [wrapped into an Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). In this case `typeof num === 'object'` – Serge Aug 19 '23 at 19:08
0

A ternary operator can help you if I understood your question well:

...
const isTernary = BigInt(x) === x ? true : false
...

you will have in your variable "isTernay" either true or false depending on whether your number is a bigint or not.

And a BigInt object is not strictly equal to Number but can be in the sense of weak equality.

0n === 0
// ↪ false

0n == 0
// ↪ true

Visit : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt for more about BigInt

Jean-Paul
  • 127
  • 2
  • 15
  • 1
    You don't even need the ternary in boolean situations (i.e. where you write `cond ? true : false`), it's enough to write `cond`. The problem is with the `try..catch`, which can't be inlined. – FZs Feb 28 '21 at 23:48
0

An easy solution would simply be (assuming you only work with numbers):

Number.prototype.bigInt = false
BigInt.prototype.bigInt = true

And then you could simply call myNum.bigInt to check.

NOTE: 3.bigInt will not work because 3. is considered a number, so you could do:

(3).bigInt
 3 .bigInt

or use it on a variable

0

Quick suggestion:

if (BigInt(n) === n.valueOf()) {
  // is BigInt
} else {
  // not a BigInt
}

Handles both literal BigInt such as 123n, and an Object-wrapped one: Object(123n). Both forms are valid BigInts with different typeof results: "bigint" vs an "object".

Serge
  • 1,531
  • 2
  • 21
  • 44