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?
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?
Share Improve this question edited Jan 2 at 12:35 Douwe de Haan 6,6463 gold badges33 silver badges51 bronze badges asked Feb 28, 2021 at 23:24 user15020827user15020827 1- You can insert a function call inside of an if statement. – Rojo Commented Feb 28, 2021 at 23:33
5 Answers
Reset to default 9You 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!");
}
});
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
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".
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)
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/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt for more about BigInt
.