5 ms·
TIL Array.sort sorts integers lexically by default. I wonder how many bugs that has caused over the years. As a side-comment, often I see JavaScript learning c
by HL33tibCe7 4y ago
TIL Array.sort sorts integers lexically by default. I wonder how many bugs that has caused over the years.
As a side-comment, often I see JavaScript learning channels and Twitters focusing a lot on JS gotchas and stuff like the prototype chain. I’ve worked on production JavaScript apps for years and have never needed to touch the JS prototype system. Time could probably be spent better elsewhere, as fun as the gotchas are. NB: I’m not necessarily saying the author of this blog is guilty of this - for all I know this is the only post like that they have written; but I have seen many channels/Twitters where this kind of stuff is post of what they discuss - possibly because of interview questions in their areas).
- dspillett 4y ago> I’ve worked on production JavaScript apps for years and have never needed to touch the JS prototype system. I think that is similar to “why do we bother teaching χ in school, I've never used it as an adult”, where the answer is a mix of: 1. For the people it is useful to, it is very useful. Those that may later be building frameworks rather than using them for instance, to save them reinventing wheels, or those coming from other languages who might otherwise have more trouble reasoning with JS as they try to use it exactly like they've used something else. 2. For the people it isn't directly useful to, at least a vague understanding of what goes on can be useful if only because you need some knowledge to know if you need to care. 3. For everyone else, perhaps myself included though I'm probably more in group 2, you taking a hit to your learning time is a sacrifice well made to make sure the people who do find it useful get it!
- amptorn 4y agoThe more surprising thing about `Array.prototype.sort` is that it both sorts the array in place and returns the (now-sorted) array. You can go a long time writing `const arr2 = arr1.sort()` without realizing that what you're doing is wrong, and the code you're writing is misleading readers about what it does.
- adamredwoods 4y agoA good case for Typescript? The string[] vs number[] type would help identify expected output.
- Szpadel 4y agonot at all, sort does not change type of those elements, string conversion is only used for comparison, so you still have number[] everywhere