DEV Community

Cover image for JS, method behind the madness.
Daniel Dennis
Daniel Dennis

Posted on • Updated on

JS, method behind the madness.

Hi There, Welcome to my first Post ☄

It all started with this meme
Alt Text

A friend of mine called me out as a now lover of JS. To be honest, i was mad(mostly because I didn't have a come back) so i decided to try it myself, only to prove him right. If you are not keen enough, JS may get away with it. Allow me to demonstrate the problem.

Given an array of numbers [6,-2,2,-7], and sort them in Ruby and in JS using the Sort method .sort().
In JS:

    const array = [6,-2,2,-7];
    array.sort();

    // The result is: [ -2, -7, 2, 6 ]

In Ruby:

 array = [6,-2,2,-7];
 array.sort();

 # The Result is:  [-7, -2, 2, 6]

By now, I hope you see it now. If you are a beginner, Given a couple of numbers and telling the computer to sort the numbers using different programming languages, one language gives them back arranged correctly (Ruby), and the other gives a not so correct answer(JS).

The reason why this happens is because, Javascript is a weird language. Not weird, Just different. Javascript's sort method uses an In-Place algorithm to sort through the array elements.

This basically means, It converts the elements in an array into a sequence of Strings, then compares the sequences of UTF-16 code units values. In simple terms, makes the numbers become individual strings of letters and arranges them accordingly.
Now, the sort method isn't broken, to see this underlying in-place algorithm work, lets sort some Strings.

Given an array of Names:

    const array = ["Daniel", "Bob", "Fizz", "Buzz", "Cynthia"];
    array.sort();

    // The result is: [ 'Bob', 'Buzz', 'Cynthia', 'Daniel', 'Fizz' ]

Tada ☄☄ It works because we are sorting strings. The default behavior of the sort method will treat everything like a String.

Worry not, You can override this behavior by use of a parameter function.
Fasten your seatbelt, it may get tricky. The function will take 2 parameters itself say (a,b), To learn more on the function and it's capabilities, read this. The function basically just checks whether a or b is smaller, bigger or equal to the other and arranges them accordingly,regardless of the data type.

To tell the sort method to treat the elements in the array as numbers, just subtract the parameters (a,b) of the parameter function of the sort method. This will arrange the elements in ascending order irrespective of the data type.
Confusing, let me demonstrate:

    //given a and b are parameters of Compare function which we pass to the sort method.
     const array = [6,-2,2,-7];
        array.sort(function(a,b){
        return a-b;
    });

    // The result will be correct, you can check 😉

Yikes, that looks weird, lets redo it with a fat arrow function like sane people.

    const array = [6,-2,2,-7];
    array.sort((a, b) => return a - b);

    // The result will be correct, you can check again 😉

Much better now courtesy of pentacular.

And there you have it, a well sorted array.

Conclusion

Moral of the story is, If you have a farm, I highly recommend you turn to farming instead, because talking to computers using JS will make you cry at one point. Ha!, just kidding, Javascript has alot of weird stuff here and there, but when you love something, you love the flaws too.
Just a tip, if you don't like all the weird parts of JS, try Typescript by Microsoft which offers Types and other cool features on top of JS.

Till Next rant,

Daniel Katungi Dennis

Top comments (15)

Collapse
 
pentacular profile image
pentacular

I think your example code is a bit off

 const array = [6,-2,2,-7];
        array.sort((a,b)=>{
        a-b;
    });
Enter fullscreen mode Exit fullscreen mode

The arrow function you've supplied here always returns undefined.

I think you intended to write this instead:

  const array = [6,-2,2,-7];
  array.sort((a, b) => a - b);
Enter fullscreen mode Exit fullscreen mode

The moral of this story is to always test your examples. :)

Collapse
 
stefanovualto profile image
stefanovualto

Same with that one ;) (missing the return):

const array = [6,-2,2,-7];
        array.sort(function(a,b){
        a-b;
    });

to work it should be:

const array = [6,-2,2,-7];
        array.sort(function(a,b){
        return a-b;
    });
Collapse
 
katungi profile image
Daniel Dennis

Haha, Oh my God. I completely missed that. Thanks for the heads up

Collapse
 
alannato profile image
AlanNato

Before the world ends.
I hope I'll write a Hello 👋 World in Js.

Collapse
 
katungi profile image
Daniel Dennis

You really should, pretty neat language when you learn it.

Collapse
 
anarchy40 profile image
Anarchy

Said the C #eron...

Collapse
 
billy_de_cartel profile image
Billy Okeyo

Some good insights on that. I love your conclusion

Collapse
 
katungi profile image
Daniel Dennis

Thank you So much for the feedback

Collapse
 
saberhosneydev profile image
Saber Hosney

Are you sure microsoft didn't "sponsor" this article to increase awareness of Typescript
〜( ̄▽ ̄〜)

Collapse
 
katungi profile image
Daniel Dennis

Yikes, They skipped Florin Pop and came to me for a promotional Blog.

Collapse
 
gwutama profile image
Galuh Utama

Ah JavaScript. A jungle of landmines. There’s even a pitfall when it’s used for sorting numbers.

Collapse
 
agiesey profile image
AGiesey

Thanks for the article! JS has some weird gotchyas and it's nice to be reminded of specific examples.

Collapse
 
katungi profile image
Daniel Dennis

You are welcome ! I hope you learned a thing or 2

Collapse
 
tillern profile image
TILLERN • Edited

Javascript is just awesome

Collapse
 
katungi profile image
Daniel Dennis

Thank you Mary Anna. We love JS regardless