DEV Community

Cover image for Sorting In Javascript | How it works under the hood ?
Swastik Upadhye
Swastik Upadhye

Posted on • Updated on

Sorting In Javascript | How it works under the hood ?


You might have guessed from the title what I'm going to talk about in this post. Sorting is one of the most popular and often used methods.

Sort() method sorts the elements of an array and returns an array in a specific sorted format.

Take a look at the following example.

let animals = [ "Zebra", "Bear", "Kangaroo", "Giraffe", "Lion", "Tiger", "Dog" ];

// Output :  ['Bear', 'Dog', 'Giraffe', 'Kangaroo', 'Lion', 'Tiger', 'Zebra']
Enter fullscreen mode Exit fullscreen mode

Oh! That's super easy 😄!

Now take a look at the following example.

let numbers = [ 1 , 50, 101 , 4 , 90 , 40 , 1000, 78 , 9 ];

// Expected  Output :   [1, 4, 9, 40, 50, 78, 90, 101, 1000]
// Actual Output :   [1, 1000, 101, 4, 40, 50, 78, 9, 90]
Enter fullscreen mode Exit fullscreen mode

Oh wait!😳 What did we get here?

Let's find out!🧐

  • From observation, one thing is clear that if the array contains the elements with string data type only, they are being sorted in ascending order.

  • Basically, what happens behind the scene is each element in an array is converted into string and then UTF-16 code equivalent value of them are compared.

  • Just to make it simple, look at the following diagram :

Image description

  • Now we get to know that why in the second example the output was so wierd.

  • Because we were not aware about the things happening under the hood.

Sort with Compare function

  • Also, there is an another form wherein sort methods can accept a callback function which is known as compare function

  • The compare function accepts two parameters ( e.g a & b ), and compare these two values.

  • If it is returning positive integer then it places b before a.

  • If it is returning negative integer then it places a before b.

  • If it is returning zero then it keeps the order as it is.

Image description

  • Now we will try to write a function for sorting an array which contains numbers.

Using Inline function

Image description

Using Arrow function

Image description

Using short-hand version

Image description

Application :

Earlier, In one of my Interviews I have been asked to write a program and the problem was :

//Given a list of non-negative integers, arrange them in such a manner that they form the largest number possible. The result is going to be very large, hence return the result in the form of a string.
// Input:
// 3 30 34 5 9
// 546 54 60 548

// Output: 9534330;
// 6054854654;


Thank you for stopping by!. If you find it useful consider sharing it. You can connect with me here : LinkedIn

Discussion (0)