Home > other >  Why ` 0n` throws an error but `-0n` does not?
Why ` 0n` throws an error but `-0n` does not?

Time:11-06

The following code throws an error in javascript:

console.log(String( 0n))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But this code runs successfully:

console.log(String(-0n))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Why 0n throws an error but -0n does not?

CodePudding user response:

So that it doesn't break asm.js:

  • Unary followed by an expression is always either a Number, or results in throwing. For this reason, unfortunately, on a BigInt needs to throw, rather than being symmetrical with on Number: Otherwise, previously "type-declared" asm.js code would now be polymorphic.

CodePudding user response:

0n is treated as (BigInt(0)), since unary means "cast to integer", and it can't automatically do that (for some reason)

console.log( (BigInt(0)));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

-0n is treated as BigInt(-0), since negative numbers can be big integers

(You need to check your console for this, since I guess there's a bug in the StackSnippets preventing BigInts from being casted to a string in the console.log call)

console.log(BigInt(-0));
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related