r/ProgrammerHumor • • Mar 20 '24

Meme areJSDevsActuallySane

Post image
14k Upvotes

554 comments sorted by

View all comments

Show parent comment

1

u/SoInsightful Mar 21 '24

Absolutely not. BigInt({}) throws "Uncaught SyntaxError: Cannot convert [object Object] to a BigInt".

The only actual explanation for the coercion is "it seemed like a reasonable idea at the time".

1

u/_xiphiaz Mar 21 '24

It is actually a very reasonable behaviour for how js works. JS when it encounters an object but is typically expecting a string will call the toString() method which is present on all objects. The base case is to return “[object Object]” unless overridden. This can be useful in some albeit niche circumstances, but more importantly it isn’t inconsistent.

The reason your example with BigInt doesn’t work is because a vanilla object doesn’t implement the valueOf method. You will find for example that you can pass a Date to BigInt and it will happily construct due to having valueOf implemented

1

u/SoInsightful Mar 21 '24

No, it's not reasonable behavior. It's in line with how JS works much of the time, but that doesn't make it reasonable behavior to begin with.

Here are some examples that rightfully don't work in JS:

Symbols fail despite having both valueOf and toString:

new RegExp(Symbol())
// Uncaught TypeError: Cannot convert a Symbol value to a string

Functions fail despite having both valueOf and toString:

BigInt(() => {})
// Uncaught SyntaxError: Cannot convert () => {} to a BigInt

1

u/_xiphiaz Mar 21 '24

Interesting, though symbols are not objects which probably explains that.

2

u/SoInsightful Mar 21 '24

We can probably find engine-level explanations for all of these cases if we dig deep. I'm just saying that they're not all "reasonable" ❤️