God save us all from JS 😑

  • 38
    Blessed are the JavaScript developers.
  • 7
  • 30
    Actually the answer it's not wrong.
    The fact is just that sort method doesn't work like we think at the first guess.
  • 35
    @osx94 Yeah. Its totally correct in js logic. But not in humans logic
  • 6
    Damn :|
  • 43
    @Shahriar JS does not have function to sort numbers, but it does have one for sorting strings. Since it is weakly typed language it will do implicit cast and sort strings.

    You can define your own compare functions (for example to sort numbers) and then it will work in a way that you wrote. You can see some nice examples here: https://developer.mozilla.org/en-US...

    Btw. Same thing happens when you do "5"+4="54" (there is + operator for strings) and "5"-4=1 (there is no - operator for strings, but there is one for numbers). There are benefits to weakly typed languages, but also negatives if you do not know language you use well enough.
  • 8
    @Shahriar alphabetical order seems pretty ok to me 😂 (i'm human btw)
  • 11
    yeah, ok MDN, but hell they write a whole novel of docs when in 99% of cases all you need is just to pass a simple anonymous fn.

    numArray.sort((a,b) => a-b); //does the job
  • 7
    Damn, took me a minute
  • 5
    Use lodash to sort an array
  • 7
    Good to know that JavaScript doesn't have a sense of what integers are. Thanks.

    This is why some people shit on weakly typed languages, they just assume things that aren't always true.
  • 4
    More like save us from people saying shit because they don't know Jack shit
  • 2
    Just wondering, how do other weakly typed languages behave in such cases?
  • 2
    @osx94 “you’re holding it wrong”
  • 6
    It literally takes 10 seconds to write a comparator function to sort it like necessary. But no, let's blame a dynamic typed language for being dynamic 🤦‍♂️
  • 3
    Just provide the correct sorting function.
  • 1
    @faheel thanks for the tip. 😊

    That's not exactly what's op doing though. His array only contains numbers. The default comparer treat them as strings. So no cross type comparison.
  • 0
    I was not even aware there is a sort function exist.
  • 0
    [6, -2, 2, -7].sort((a, b) => a - b)
Add Comment