Explaining the meme

Internet is made of millions of memes flowing everyday, so, devs create a ton of new images showing how their code doesn’t work,
the server is down or even the programming language is broken or annoying. ?

This particular meme comes from Javascript enviroments inside web and application development.

Javascript lack variable types, so casting, parsing and all that stuff is pretty tough

So someone discovered that using the default parseInt(); function with a number 0.0000005 returns the 5 as result instead of 0.

imagen

Ok, but how is that even possible? ?

To solve this mistery I make two scripts in javascript and python that share the same logic.

Python uses int() to parse so I use it here. But I realized that the function is protected
against using a float as an input, showing the following error.

imagen

Ok so, thats it, javascript is broken ??

Maybe this is not that simple.

Okay so python is protected. But I solve this issue using float() function and now is running:

Code:

imagen

Output:

imagen

The output is showing, but using scientific notation

Getting closer to the solution ?

SO! python is using another notation when parsing number is small enought. Let’s try parsing with parseFloat() in javascript instead.

imagen

Excellent! The number is shown in the correct way now. BUT IN SCIENTIFIC NOTATION

imagen

Okay but what’s Javascript doing inside the getInt() function? ?

That’s the funny part, it seems that javascript is using the parseFloat() function that
returns 5e-7 and then getting the first numbers before the ‘ilegal characters’

We can see this behaivour here with the following snipet:

Code:

imagen

Output:

imagen

The conclusion ?

Using javascript parseInt() to parse a float inside a String is extremelly incorrect.
You MUST be using parseFloat() and then trunc the number if you want.

imagen
imagen

So using the right tools to do the right things, that’s the key.

The hidden truth for javascript developers, compilation errors! ?

Typescript is awesome, it makes such a difference coding with all the goodies of javascript
and the security of the variable types.

That’s why I migrated all my javascript projects to it, and I’m very happy with that.
So I tried using parseInt() with the float inside… and typescript throw a compilation error!

imagen

How amazing is that?

I hope you enjoy this experiment!?

  • Akrck02

GitHub

View Github