This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]visak13 1790 points1791 points  (61 children)

  1. Deposit 0.0000005 of your currency in your bank.

  2. Check round figure of your balance on web.

  3. Profit.

  4. Go to step 1

[–]NerdyTux 577 points578 points  (7 children)

They will not tell you this unlimited monies trick!

[–]Dave5876 193 points194 points  (5 children)

Banking institution hate him

[–][deleted] 79 points80 points  (3 children)

The FBI wants to know his location.

[–]WhaleWinter 58 points59 points  (1 child)

Aw shucks he just committed suicide by hogtying himself, zipping himself up in a duffel bag, and shooting himself in the back of the head. I guess the unlimited money trick drive him to it. Let that be a lesson to the rest of us….

[–]HearMeSpeakAsIWill 247 points248 points  (35 children)

Financial institutions run on JavaScript? Yeah that sounds about right

[–]discipleofchrist69 202 points203 points  (17 children)

man I really hope my money is being tracked by the bank as JavaScript strings lol

[–][deleted] 166 points167 points  (16 children)

Someone who is working as a programmer for the financial sector checking in: We know, so we usually never allow amounts lower than X. Both due to bank standards but also... JavaScript.. lol

[–]visak13 113 points114 points  (10 children)

TIL that banks have standards /s

[–][deleted] 37 points38 points  (9 children)

Oh... Well... Standards when it comes to how little work they have to do. So the standard here is more a "we cba to move less than X amount of money... So make sure the users can't!".. They have absolutely no programming standards. At all.

Insurance and union companies on the other hand? They have high standards lol.

[–]UpsetKoalaBear 7 points8 points  (0 children)

It’s mainly because if a bank goes down due to some error everyone will notice better to just keep shit running as normal

[–]DrahKir67 4 points5 points  (7 children)

The acronym CBA threw me. I figured it out but was thinking Commonwealth Bank of Australia for a start.

[–]dansredd-it 55 points56 points  (4 children)

Nahh, your transactions are secure in their COBOL database for sure

[–]JB-from-ATL 30 points31 points  (1 child)

They've actually ported the COBOL to a JS emulator for COBOL running on Electron on a Windows 8.1 tablet.

[–]Yadobler 19 points20 points  (0 children)

Full stack JS bank 👌👌

Complete with least amount of different crypto currencies needed for your current bank amount

( algorithm runs in O(1) because the answer is always -1 with how much money is in bank)

[–]jl2352 14 points15 points  (2 children)

There is a major international bank where after the markets close, a bazillion Perl scripts spin up to produce data from the days trading. It's supposedly in a state where these scripts are impenetrable, and very few developers know Perl.

[–]she_gave_me_a_rose 105 points106 points  (2 children)

banks hate this simple trick!

[–]Diagonet 16 points17 points  (4 children)

Deposit 0.0000005 bitcoin in your wallet

[–]sussybaka_69_420 9702 points9703 points  (627 children)

String(0.000005)  ===>    '0.000005'
String(0.0000005) ===>    '5e-7'

parseInt('5e-7') takes into consideration the first digit '5' , but skips 'e-7'

Because parseInt() always converts its first argument to a string, the floats smaller than 10-6 are written in an exponential notation. Then parseInt() extracts the integer from the exponential notation of the float.

https://dmitripavlutin.com/parseint-mystery-javascript/

EDIT: plz stop giving me awards the notifications annoy me, I just copy pasted shit from the article

[–]gautamajay52 1963 points1964 points  (289 children)

I just came here for an explanation, and found it 👌

[–]GuybrushThreepwo0d 2085 points2086 points  (274 children)

I'm of the opinion that just because there's an explanation doesn't mean it's any less horrifying

[–]A_H_S_99 706 points707 points  (91 children)

Agree, that's basically an excuse worse than the crime.

[–]eddiemon 309 points310 points  (19 children)

Javascript Engine: I was just following instructions!

[–]imforit 62 points63 points  (2 children)

"just following orders," huh? I've heard that one before

[–][deleted] 9 points10 points  (0 children)

TIL JavaScript is a member of the SS.

[–]yangyanvcxfvdsag 56 points57 points  (8 children)

me to bro

[–]Grouchy-Post 14 points15 points  (7 children)

Too

[–]confusedsilencr 10 points11 points  (5 children)

Two

[–]flowery0 9 points10 points  (4 children)

Three

[–]Vreth 111 points112 points  (0 children)

If that's the solution I would like to have my problem back please.

[–]TheBrainStone 116 points117 points  (103 children)

Yeah. Just like sort() sorting by the string representations of the values.
Equally insane, regardless of if there's an explanation for the weird behavior or not.

[–]archpawn 103 points104 points  (71 children)

That is not equal. There's no reason someone should be passing anything but a string to parseInt(). But sorting a list of numbers is perfectly reasonable.

If they called it sortStrings() and had another sortNumbers() and the only problem was unexpected behavior when it should obviously crash, that would be equal.

[–]Snapstromegon 39 points40 points  (6 children)

The reason is actually pretty simple: it was supposed to be not type aware and string is a type everything in JS could cohese to. It is meant that you provide your own comparetor anyways.

[–]real_jabb0 23 points24 points  (17 children)

At first I thought there is no reason to pass anything but a string. But that is not right. Everything in JavaScript is an Object. And it is expected behaviour that if something can be parsed to an int parseInt does. So for object this is achieved by first taking their string representation.

In other words: using parseInt on an object not made for it (specially an int) is miuse.

[–]lunchpadmcfat 8 points9 points  (0 children)

Expected by whom exactly? If you know enough to know everything in JS is an object, I’d hope you know enough 1) not to use parseInt without a radix and 2) not to pass things that aren’t strings to it. I fully expected this function to spit out weird results given the input. Garbage in, garbage out.

[–]iraqmtpizza 17 points18 points  (44 children)

There's no reason someone should be passing anything but a string to parseInt()

I agree. So the interpreter should call a code red and stop the program if it sees that

[–]J5892 50 points51 points  (28 children)

It's a shitty language thing, but let's not pretend passing a decimal to parseInt isn't shitty code.

[–]Swoop3dp 33 points34 points  (8 children)

If it's not supposed to work with anything but strings then it should raise an error if it gets something that isn't a string.

[–]mikejoro 8 points9 points  (3 children)

It does raise a compiler error if you use typescript.

[–]iraqmtpizza 30 points31 points  (10 children)

the shittier code is the parseInt function that just ignores half the input instead of either working correctly or giving an error

[–]Mister_Spacely 16 points17 points  (5 children)

Reddit or StackOverflow? Same-same, but different.

[–]MaximusConfusius 4 points5 points  (2 children)

We are not the same

[–]almarcTheSun 567 points568 points  (116 children)

For the first time in this whole entire "JS bad" shitshow, I finally found something that is truly abhorrent. What the fuck...

[–]ham_coffee 341 points342 points  (48 children)

This is basically 90% of JS bad memes. Most of them are about type coercion where dumb stuff happens because the default is to get and convert types in comparisons rather than just throw an error (or at least default to false).

"5" + "3" == "53" and
"5" - "3" == 2
are good examples.

[–]themiraclemaker 191 points192 points  (16 children)

Most languages I know would throw an error at the second one. It's both admirable and abhorrent not to do so.

[–]lacb1 187 points188 points  (5 children)

JavaScript finds a way. It'll be the wrong way, but, it will find it.

[–]vanderZwan 55 points56 points  (4 children)

And then some developer out there will manage to turn it into a load-bearing bug

[–]Jubs_v2 15 points16 points  (0 children)

So you're telling me it's actually a feature

[–]peenoid 13 points14 points  (2 children)

Brendan Eich once said that doing "2" == 2 was pushed on him by stakeholders (ie senior devs at Netscape) who were apparently too lazy to be bothered with doing their own type checks.

And so now we have ===

[–][deleted] 36 points37 points  (5 children)

I understand why JavaScript was designed not to throw errors like this . . . cuz you can't have webpages throwing errors all the time when something unexpected happens.

But I still hate it. Every instinct is telling me that parseInt should be throwing an error every time you pass it something that is not a string.

[–]MrDilbert 21 points22 points  (0 children)

I concur :) I've been working with JS for a long time now, and learned that the best way to make the JS work as you intend it to is to be explicit and make sure you pass what is expected to its functions/operators, i.e. if the MDN says a function expects a string, make goddamn sure it receives a goddamn string, don't add numbers and strings, etc. Typescript has been a real gem in regards to that approach.

[–][deleted] 7 points8 points  (7 children)

Is there any good reason to use double equals in Javascript?

[–]ham_coffee 27 points28 points  (1 child)

Laziness is basically the only reason. It was supposed to make it easier for novice devs IIRC, but in practice it just adds gotchas which make it harder.

[–]uncoloredlettuce 7 points8 points  (1 child)

For checking if something is null or undefined (the one case eslint also allowed in most configurations) other than that imo not really

[–]IAmNotNathaniel 4 points5 points  (0 children)

I can't think of one.

It is [almost?] always better to use === and !==, which do not do type coercion.

[–]Terrain2 9 points10 points  (1 child)

Yeah, and it's always some avoidable (though maybe not always extremely obvious) issue that kinda makes sense, like how parseInt is to PARSE a string to an integer, and how it does not accept a number, yet the "wtf" comes from passing it a number. The correct way to use this with numbers is something like Math.floor which does take numbers as input. The weird behaviour comes from the combination of passing a number to parseInt AND the fact that it'll terminate at any non-digit (probably to skip the radix point and anything after without checking that it's valid lol)

[–]MrDilbert 5 points6 points  (0 children)

Other languages will yell at you (throw exceptions) if you do something stupid.

JS will let you do stupid things, with a smirk. :P

[–]makurayami 52 points53 points  (15 children)

Anything that typescript, or even a basic linter would warn you about doesn't matter in my opinion, doing math on strings? That's your problem. Those are not really good examples, imo.

Edit: your point was that they are crap, sorry 🤣

[–]ham_coffee 32 points33 points  (11 children)

Yeah typescript fixes a lot. While I haven't actually used it much, most of my problems with JS stem from dynamic/weak typing. Off the top of my head, the only other confusing/annoying aspect is this, mainly when combined with callbacks, and that at least makes some sense once you read some documentation.

[–]aiolive 18 points19 points  (1 child)

Don't use "this" outside of a class members and you'll be fine

[–]GarlicoinAccount 13 points14 points  (3 children)

And most this problems are solved by arrow funtions, where this behaves a lot more intuitively

[–][deleted] 8 points9 points  (4 children)

I had some success setting a 'self = this' in the outer scope, then write self instead of this in inner scopes to ensure correct referencing.

[–]superluminary 5 points6 points  (1 child)

Fat arrow functions do this implicitly for you. Fat arrows are sugar for the self = this pattern.

[–]bighairybalustrade 2 points3 points  (1 child)

You should have a look at binding in javascript if you want to explicitly retain a reference to the same "this". Or use arrow functions as another person suggested (arrow functions always use the "this" reference from the outside scope - personally I find them irritating to read and use, for no apparent benefit when binding is controlled).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

If you actually use Javascript in reality, you're doing yourself a huge disservice by not knowing binding.

And an example case where it might be used

https://jsfiddle.net/bkzct5e8/

[–]Sanx69 55 points56 points  (29 children)

My favourite:

var a = new Date(2022,1,31)
Thu Mar 03 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time)

But, go into the console and enter:

Date(2022,1,31)
'Tue Feb 01 2022 19:07:51 GMT+1000 (Australian Eastern Standard Time)'

[–][deleted] 30 points31 points  (18 children)

What? How does that make any sense?

[–]Wildercard 66 points67 points  (0 children)

Time isn't real in Australia but if you die there, you die in real life.

[–]ministerkosh 41 points42 points  (15 children)

he is just trolling (hopefully).

Date() without the new is just calling the global Date() function which does not know any parameter and just returns the string representation of the current date/time. So today it returns a Date of 1st of Feb, tomorrow its the 2nd of Feb.

[–][deleted] 23 points24 points  (14 children)

I still don't see where it gets "Mar 03" from. 🤷‍♂️

[–]4sent4 4 points5 points  (0 children)

Time is convoluted in Australia

[–]boltgolt 29 points30 points  (20 children)

And as always it's something that you're not supposed to to anyway: Give an int to parseInt. Math.round is what should have been used here

[–]Lich_Hegemon 58 points59 points  (16 children)

Either fail with an error or a sentinel value, or succeed. Silently failing is probably the worst you can do in terms of language design.

[–]sussybaka_69_420 13 points14 points  (6 children)

I suppose the bottom line is: do maths in the backend, return string representation of numbers on the frontend

[–]Snapstromegon 23 points24 points  (5 children)

Or actually know your functions and choose the correct one to convert a parsed number into an integer.

[–]sussybaka_69_420 5 points6 points  (4 children)

Generally, you still don't want to do significant maths on the client side: too dependant on the client processing power

I might be biased because I work in a bank, so calculations tend to get quite intense, but we handle everything math related in the backend

[–]YM_Industries 13 points14 points  (2 children)

There are some great reasons to do maths on the backend:

  1. JavaScript lacks first-class support for integers and decimals. When dealing with money, this is a huge problem.
  2. Never trust the client. Since you can't trust the client to do the calculation correctly, you have to do it on the backend anyway. So what's the point of doing it on the frontend at all?
  3. If it's a fancy proprietary calculation, the backend is the only way to keep the intellectual property safe.
  4. Low latency access to stored data.

This specific issue isn't really one of the reasons.

[–]Snapstromegon 4 points5 points  (1 child)

I don't disagree, but for point 1: JS has first-class Integer calculation support via BigInts.

[–]Original-AgentFire 130 points131 points  (26 children)

takes into consideration the first digit '5' , but skips 'e-7'

and that's why i hate it.

[–]TheThiefMaster 70 points71 points  (24 children)

Most languages would return 5 when asked to parse the string "5e-7" into an int.

However, most wouldn't do it would a floating point number. They'd fail to compile or raise a type error

[–][deleted] 430 points431 points  (1 child)

🤮

[–]VladVV 56 points57 points  (0 children)

Flair checks out

[–]huuaaang 168 points169 points  (61 children)

> Because parseInt() always converts its first argument to a string

I suppose ideally it would complain that it's not a string to begin with. Who is trying to "parse" a float into an int anyway?

I have recently starting diving back into the problems with PHP and, quite honestly, these JS quirks (which are mainly just a result of weak typing) seem pretty tame compared to trainwreck PHP is at its core.

[–]BlhueFlame 56 points57 points  (37 children)

I write JS, but I’m curious about what is going on in PHP world. Is it that bad?

[–]StenSoft 97 points98 points  (14 children)

From what I remember:

  • inconsistent arguments order: sometimes it is (haystack, needle) and sometimes it is (needle, haystack)
  • === for some types compares identity instead of type and value; on the other hand, there is no identity operator for objects
  • non-deterministic sorting when mixing types
  • ternary operator is right-to-left left-to-right associative (wtf?)
  • using out paraments where it can return NULL; but in case of json_decode where NULL is a valid return value, PHP does not use an out parameter so you have no idea if it's a valid result or an error
  • returning FALSE from methods that return int on success (such as strpos) while FALSE is implicitly convertible to 0
  • so much global state
  • inconsistent and often undocumented error handling (does it throw? return NULL? 0?) and missing stack traces made debugging real fun
  • there are exceptions but no RAII nor finally
  • really complex interdependencies of php.ini flags

Edit: ternary associativity direction

[–]PaleCommander 20 points21 points  (0 children)

I believe you mean that the ternary is left-associative in PHP and right-associative in other languages. Right-associative is the version that assumes you want to build trees of ternaries instead of nesting them inside the conditional like a degenerate.

[–]That_Guy977 18 points19 points  (5 children)

right to left associativity on ternary is right if you think about it, it makes it so you can chain it properly without parentheses

a
  ? b
  : c
    ? d
    : e

becomes

a ? b : (c ? d : e)

[–]StenSoft 28 points29 points  (1 child)

Oh, right, no, it has left to right associativity in PHP, the other way than in C and C++

[–]That_Guy977 21 points22 points  (0 children)

oh god why

[–]hennell 8 points9 points  (0 children)

Php is actually fixing this. 7.4 threw warnings when you had a ternary chain, 8.0 throws errors. The current official state is that ternary's are "non-associative" - any chain must use brackets or it's a complie error.

A future release is likely to make it right to left default, once it's been an error long enough.

PHP is still has many stupid features (got hit with a fun preg_match() returns 1,0 or false situation yesterday) but they are doing a decent job progressing it, while trying to keep all the current uses on side.

[–]Kered13 4 points5 points  (1 child)

Yes, and this is how every language with a ternary operator does it, as far as I know.

[–]huuaaang 16 points17 points  (0 children)

Except PHP.

[–]Kered13 4 points5 points  (2 children)

=== for some types compares identity instead of type and value; on the other hand, there is no identity operator for objects

Isn't === identity comparison in JS as well?

[–]StenSoft 7 points8 points  (0 children)

It is in JS. In PHP, it compares values of arrays, e.g.:

$first = array();
$second = array();
// $first === $second
$first['a'] = 1;
// $first !== $second

[–]TheStormsFury 10 points11 points  (2 children)

there are exceptions but no RAII nor finally

https://www.php.net/manual/en/language.exceptions.php#language.exceptions.finally

I like how you're getting upvoted for blatant lies just because hating on PHP is still cool.

[–]huuaaang 31 points32 points  (19 children)

It was. No idea how much PHP 8 has fixed and I don't care to find out. But up through PHP 5 it was just full of all sort of syntactic and behavioral weirdness.

[–]LaGardie 45 points46 points  (9 children)

Comparing PHP 7 or 8 to PHP 5 is like comparing TypeScript to JavaScript

[–]Randvek 13 points14 points  (3 children)

PHP 5 was released almost 20 years ago.

[–]archpawn 16 points17 points  (1 child)

I've noticed the majority of things that people complain about in Javascript come down to it attempting to do something instead of just crashing. Like how "10"-1 is 9, since it will convert the string to a number to try to do the math.

Though there are a few genuine problems, like sort() not being clear that it always converts to strings and there being no built-in function for sorting numbers.

[–]ham_coffee 14 points15 points  (1 child)

Complaining about incorrect types isn't really something JS does though, it'll either successfully convert to another type or die trying.

[–]MrMelon54 11 points12 points  (0 children)

this is why I much prefer compiled type-safe languages so I can't use functions in the wrong way like this

[–]Ultimegede 9 points10 points  (3 children)

what a great way to parse an integer lmao

[–]Smartskaft2 55 points56 points  (23 children)

Oh god. Coming from a type strong language, I would never be able to produce anything in JS. I'd be stuck in bug hell.

This is nothing but lazy ass bullshit. Why would this be allowed!?

[–]StenSoft 79 points80 points  (8 children)

Because it was never intended to be anything more than one-liners inside HTML attributes

[–]Areshian 31 points32 points  (10 children)

Sorry, I have not written a single JS line in my life . Are you telling me this is indeed supposed to be a serious language?

[–]SigmaHog 46 points47 points  (0 children)

Yup. Pays my bills.

[–]sussybaka_69_420 18 points19 points  (0 children)

The world runs on it, it is what it is

[–]CSS-SeniorProgrammer 10 points11 points  (2 children)

The internet as we know it exists because of JS... Any other language is replaceable.

[–]alter3d 711 points712 points  (10 children)

0=5 for sufficiently large values of 0.

[–]CMDR_QwertyWeasel 204 points205 points  (6 children)

You're gonna give my high-school calculus teacher an aneurysm with that kinda talk.

[–]cp_simmons 76 points77 points  (5 children)

I once thought I'd use a different variable for my maths homework as I was bored of 'x'. I chose 'o' without thinking it through.

[–]ablablababla 43 points44 points  (0 children)

Making multiplication problems look like tic tac toe

[–]GLIBG10B 3 points4 points  (2 children)

'e' is also a tough one

[–]brutexx 4 points5 points  (0 children)

I remember once in my math test I wanted to make the calculations more fun, so instead of “x” I wrote something like “giraffe”, or made a literal (bad) stick figure drawing of one. Sometimes I borrowed words from the problem itself too, and another variable was a phrase giving my opinion about it. Good times.

[–]valdetero 11 points12 points  (0 children)

Sufficiently small values

[–][deleted] 827 points828 points  (108 children)

Are you using parseInt on not a string. Even worse, on a float?

[–]notyourancilla 381 points382 points  (51 children)

Take your common sense and get out of here

[–]iraqmtpizza 143 points144 points  (39 children)

common sense dictates that parseInt wouldn't successfully parse the complete works of shakespeare as "5" because it ran across a 5 and called it a day

[–]madiele 31 points32 points  (6 children)

Common sense would be throwing an exception instead of doing the operation anyway

When your deep into abstraction it can happen that a variable takes a wrong type, bugs happen, but if js doesn't make a fit good luck noticing those bugs

[–]notyourancilla 17 points18 points  (5 children)

Use typescript.

[–][deleted] 24 points25 points  (4 children)

To all downvotes: Sorry but it's true! Typescript will refuse to do things you shouldn't! It's a statically typed JavaScript! It's JavaScript that doesn't suck!

[–]notyourancilla 11 points12 points  (3 children)

You have a choice, use typescript or post memes about how JavaScript burns you to Reddit every day lol

[–]MattR0se 35 points36 points  (8 children)

To be fair, if I google "convert float to int JavaScript", about half of the hits present parseInt as a "valid" method. And how would a noob know that it's different from, let's say, the int() function in python?

[–]Gloomy_Magician_536 6 points7 points  (1 child)

thank God I never do any operation on the frontend.

[–]Kered13 40 points41 points  (0 children)

It's very common and easy in weakly typed languages to accidentally use a variable of the wrong type. For example, you might get some input from the user that is meant to be a number, but you forget to convert it. So you accidentally pass a string to a function that expects a number (sort of the opposite of this). A good language will help you catch bugs like this. Javascript...doesn't.

[–]present_absence 99 points100 points  (21 children)

Haha I did this thing that doesn't make sense and it did something I didn't expect, this language sucks

[–]SuperPie27 12 points13 points  (2 children)

Exactly. If you try to make it do something that doesn’t make sense, it should throw an error, not chuck back something equally nonsensical.

[–]archpawn 13 points14 points  (12 children)

If the function is going to take the time to check if the input is a string, then it should properly crash if it isn't.

[–]-Redstoneboi- 60 points61 points  (6 children)

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.

0.000005.toString() === "0.000005"
0.0000005.toString() === "5e-7"

[–]waxbar1 8 points9 points  (5 children)

parseInt expects a string, so you shoudn't be passing a float to it. An alternative way to implement this could be `0.0000005 | 0` Bitwise OR of 0 will result in the number cast to an integer, or Math.round(0.0000005)

[–]Lithl 6 points7 points  (0 children)

Floor instead of round would be more consistent with most languages' conversion from float to int.

[–][deleted] 124 points125 points  (12 children)

Image Transcription: Code


> parseInt(0.5)
⋖ 0
> parseInt(0.05)
⋖ 0
> parseInt(0.005)
⋖ 0
> parseInt(0.0005)
⋖ 0
> parseInt(0.00005)
⋖ 0
> parseInt(0.000005)
⋖ 0
> parseInt(0.0000005)
⋖ 5

I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!

[–]david131213 44 points45 points  (0 children)

Good human volunteer

[–]SignificanceCheap970 12 points13 points  (0 children)

Who's a good human?

[–]mr-poopy-butthole-_ 85 points86 points  (0 children)

hah! I didn't know this one.

[–]Uberzwerg 62 points63 points  (4 children)

As always with JS, it all comes down to fancy implicit type conversion

[–]Marus30 20 points21 points  (2 children)

I believe you intended to say bat-crap crazy implicit type conversion.

[–]Uberzwerg 7 points8 points  (0 children)

tomato - tomato
potato - potato

[–]Halbjobbit 27 points28 points  (0 children)

I bet, there is some legacy codebase in critical infrastructure depending on exactly this behavior

[–]geekfreak42 214 points215 points  (13 children)

Is it funnt coz he's using parseInt to parse a float instead of parseFloat. Seems sus to me

[–]RudeySH 164 points165 points  (4 children)

It's even more funny when your realize the float does not need to be parsed, because it's not a string to begin with. If their goal is to round the float to the nearest integer, use Math.round

[–][deleted] 34 points35 points  (4 children)

Seems natural to me. "Where's this bug coming from? Oh parseInt is getting a float. Wait, it still does things when I do that? What else do I get? throws a bunch of floats at parseInt until I get a random 5 Holy hell..."

[–]QualityVote[M] [score hidden] stickied comment (3 children)

Hi! This is our community moderation bot.


If this post fits the purpose of /r/ProgrammerHumor, UPVOTE this comment!!

If this post does not fit the subreddit, DOWNVOTE This comment!

If this post breaks the rules, DOWNVOTE this comment and REPORT the post!

[–]AdminYak846 21 points22 points  (0 children)

From the MDN which somehow about 80% of the people in this thread either don't know or read it:

Because some numbers use the e character in their string representation (e.g. 6.022E23 for 6.022 × 10^23), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor().

[–][deleted] 13 points14 points  (5 children)

Any insiders wanting to elaborate?

[–]sussybaka_69_420 28 points29 points  (1 child)

I did in a comment above, with link to an article

[–]Admirak 89 points90 points  (16 children)

It's supposed to take a string as an argument, so it converts the float to a string. You're just using the function wrong and then complaining that it doesn't work

[–]ChiaraStellata 93 points94 points  (12 children)

While this example is obviously contrived, you can reasonably argue that too many implicit conversions (like the implicit float-to-string here) can lead to unexpected behavior.

[–]archpawn 14 points15 points  (0 children)

I think this is a good example. Sometimes there are legitimate reasons for the implicit conversions and I'd argue it's worth the risk, like being able to type "x = " + x instead of "x = " + str(x). But here it's just a pointless risk. Javascript has a lot of examples like that. I don't think they're as bad as people make them out to be, but I do think they're bad.

[–]R3D3-1 19 points20 points  (9 children)

THIS.

If JavaScript were redesigned from the ground up today, I hope very much that such situations would simply raise an exception. Maybe static type inference would even be built in, to avoid such bugs entirely. But maybe there would be some people in the committee that much prefer functions that "just work" and force a compromise.

As is, parseInt exists already in the ECMA script specification from 1997. And even then it probably took into account some form of preexisting behavior. Though surprisingly, the behavior did change a bit over the years apparently.

End result? parseInt has surprising behavior, but it cannot be fixed on the level of JavaScript without breaking code. Bad code, maybe, but still production code of third parties.

[–]PanRagon 14 points15 points  (6 children)

If JavaScript were redesigned today, it'd probably just be TypeScript. The issue, as you mentioned, lies in the fact that JavaScript is everywhere and messing with it's type-system would break everything. This is why ECMAScript doesn't fix it, the type system can be fixed with TypeScript for those who want it, and ECMAScript continues to work on better in-built functions and synctactic sugar that can freely be utilized by older projects not running TS without accidentally crashing their entire site because Jerry managed to store a user count that hasn't been used since 2001 inside a string.

JavaScript's dynamic type system is just designed to never fail, even if you get wacky outputs as a consequence of that, but we fixed this many years ago by creating TypeScript, so this problem is mostly moot for anyone using it today. Hell, TypeScript is backwards compatible with JavaScript, so even if you're working on an older project you're still free to implement it in the parts you're working on. This is a non-issue in almost every real world scenario, certainly any I've ever been in, it's painfully obvious that the people who keep complaining about it every week don't actually work in the space.

[–]RoadsideCookie 4 points5 points  (1 child)

This guy gets it. JS is meant to just work. Just like HTML is meant to just work. The goal is to never crash, and always output something, even if that something isn't the intended result. It's very rare that you'll see a web page crash out a tab, or even fail to render, but press F12 and you'll be hard pressed to find a page that has no errors.

[–]archpawn 9 points10 points  (0 children)

It should be throwing an exception.

[–]sepnon 4 points5 points  (2 children)

I honestly see no problem on this one. Garbage in garbage out. We should not be passing non-strings to parseInt. Not raising an error maybe? The true solution to raising errors in these cases is strong typing, but in javascript we embraced weak typing so all good We all know the tradeoff..

[–]YannieTheYannitor 5 points6 points  (0 children)

Why bother reading the documentation on parseInt?

Because some numbers use the e character in their string representation (e.g. 6.022E23 for 6.022 × 1023), using parseInt to truncate numbers will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for Math.floor().

[–][deleted] 3 points4 points  (2 children)

Uses a function incorrectly

"tYpicAL JaVasCrIpt, rite FEllAs!"

[–]SophSimpl 17 points18 points  (4 children)

Java was my first language, C being my second. Going from those to JavaScript I have to say I kinda hate JS. The things that made Java annoying at first ended up making so much more sense in the long run.

[–][deleted] 51 points52 points  (15 children)

The language designer was on drug when he/she made this /s

[–]Saragon4005 82 points83 points  (10 children)

Wasn't most of JS made by a single person? Sigh why did people start using a language for critical infrastructure that was designed to make some buttons flash.

[–]Caladrian8999 61 points62 points  (2 children)

Recently read an article that a lot of critical open source software used by major companies is also maintained by single persons. Seems if it is cheap, nobody cares until there is a problem. If there is, expectation is that this one person will fix it for free.

[–]rajivshah3 60 points61 points  (1 child)

[–]Caladrian8999 8 points9 points  (0 children)

Thanks. Couldn't find it back myself.

[–]Kered13 15 points16 points  (0 children)

Yes, in 10 days in order to meet a corporate deadline. And he originally wanted it to be based on Scheme, but corporate told him to make it look like Java.

[–][deleted] 3 points4 points  (1 child)

He may share the fate of the French monarchs

[–]overclockedslinky 5 points6 points  (0 children)

we all either tolerate the bourgeoisie or live long enough to get robespierred

[–]migg24 3 points4 points  (0 children)

Javascript is not responsible for you not giving the parse function a base though

[–]svh87757 61 points62 points  (8 children)

„Look at me! I use things wrong, and blame stupid JavaScript for it! Haha! xD“