Simplifying IT, Amplifying Knowledge

Javascript pain

Published on: 10 January 2025 Category: programming

As I really like programming in Javascript, sometimes it makes me really angry. And one of the things is that the typing can (or cannot in some areas) make a real mess.

I do not really care about the ability to use numbers wrapped as string, as it is really easy to make numbers from string just by multiplying it by one, but the typing also has some big disadvantages.

The biggest problem, for me, are arrays. Which can be arrays, but without any casting they can be also strings, which is sometimes really mess. And the biggest problem, is some kind of auto-casting on background, which is really mysterious, if you are not able to go really deep and discover the reason, whi that happens.

This is one of the really weird examples:


[] * []         // -> returns 0
This is weird..




[8] * [8]       // returns 64
This is even more weird..


[8,1] * [8,1]   // return NaN
And this is then the peak of weirdness



And the reason? Yup.. it really has a reason

And the reason? Yes... there is a reason.

Before multiplication, the variables (arrays) are passed internally through .toString(). And as the string is then cast to string.... And as I mentioned at the beginning, the arrays can sometimes be a string on its own... so the toString method joins the number in array just separated by comma. And if there is only one index, then it just returns the number.

So the step for these examples are:

"" * ""
"8" * "8"
"8,1" * "8,1"


Can you see it now? When multiplying the string, it tries to turn it into a number, so the empty string turns into 0, the eight in the string turns into 8, and ? The 8.1 converts to NaN because programming uses a comma instead of a dot. So... this is it. F*c*ing disappointing


Comments: