how to check if a number is a BigInt in javascript

Viewed 1428

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?

3 Answers

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!");
  }
});

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

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

Related