In JavaScript there are two typed array constructors that can store rather large numbers:
const longs = new BigInt64Array()
const doubles = new Float64Array()
They both represent arrays of 64-bit signed integers and floating point numbers, respectively.
Is there any reason to use BigInt64Array
if I’m not storing numbers larger than Number.MAX_SAFE_INTEGER
?
The only upside I can think of to use BigInt64Array
(even if your numbers are less than Number.MAX_SAFE_INTEGER
) is if you want to enforce an integer type while storing your numbers, since the constructor will throw an error if one of the elements is a floating point number:
const arr = new BigInt64Array([900719925.4534]);
// Uncaught TypeError: Cannot convert 900719925.4534 to a BigInt
However, the downsides are that for each known integer you want to add, you have to remember to append n
to it like so:
const arr = new BigInt64Array([523235n, 1093n, 3238n]);
In addition, if only the runtime knows the integers, you have to use the BigInt(value)
function to convert them to the proper type:
const arr = new BigInt64Array([BigInt(a), BigInt(b), BigInt(c)]);
The upside to Float64Array
is that it works right out of the gate with primitive JavaScript numbers (no number literal suffix or converter function is required).
Is my reasoning correct on the usefulness of BigInt64Array
?