javascriptbigint

how to check if a number is a BigInt in javascript


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?


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