'Why are these two values different?

I recently had a lecture where we covered BigInts and how to declare them using either the constructor or appending an 'n' to the end of the number. I felt as though I understood the lecture well, until I encountered this strange behavior.

Could someone explain to me why there's a difference here?

console.log(239723948723409274092834987230917298720394203874n);
console.log(BigInt(239723948723409274092834987230917298720394203874));

//OUTPUT
239723948723409274092834987230917298720394203874n
239723948723409282517569648409973454535932248064n

It's the same number in both use cases, but the output is different. I suspect that this is actually appropriate behavior because the argument passed to the constructor has to be calculated by the engine before the constructor uses it?

I'm not sure if that's correct though, so that's why I'm here.



Solution 1:[1]

Numeric constants (either plain numbers or big int values with the trailing n) are parsed and evaluated as per their type before the program even runs. If you put a big int constant in your program, the parser creates code that runs with a big int value. If you put a plain number in your code, the parser creates a plain 64 bit floating point number, like all old-school JavaScript numeric values.

Thus when you call BigInt() with a constant that does not have the trailing n, which would tell the parser to make a big int and not a plain number, you're creating an expression that's evaluated before the function call. It's a plain number, so you lose a whole lot of precision before your new big int value is even created.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pointy