javascriptif-statementbigint

How To Check If A Number Is A BigInt In JavaScript?


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

I know there is this try/catch solution:

function isBigInt(x) {
    try {
        return BigInt(x) === x;
    } catch(error) {
        return false;
    }
}

I want to implement the test directly in an if statement and not as a function.

Can someone help me with this?


Solution

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