8

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?

1
  • You can insert a function call inside of an if statement. Commented Feb 28, 2021 at 23:33

5 Answers 5

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

A bigint can also be wrapped into an Object. In this case typeof num === 'object'
@Serge in that case, (value).constructor === BigInt should work.
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

Comments

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".

Comments

0

If you're only interested to see if the value is a native BigInt, I think @Rojo's suggestion to use

typeof value === 'bigint'

is the best.

But if the BigInt is provided by a custom class (a 'polyfill') then the typeof expression will evaluate to 'object'.

But the following does work:

value.constructor === BigInt

(Note: value instanceof BigInt does not work for the native BigInt type)

Comments

0

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

const isBigInt = BigInt(x) === x;

Your variable isBigInt will either be 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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.