Sorting an array in numerical order

For the most part, sorting numerical values means you want them sorted numerically. JavaScript understands that, and in a while, you will understand how to.

Sorting an array in numerical order still involves the same sort() method, with a little twist:


"functionname" represents the returned value of a special function created specifically for the sort() method. A function like this has the following format:

function myfunction(a,b){

Lets first put all this together and sort an array numerically, before anything else:

function sortit(a,b){
var myarray=new Array(70,43,8)
//myarray[0] is now 8, myarray[1] is now 43, myarray[2] is now 70

Ok, so what's "a" and "b", and why all this weird additional syntax? Well, "a" and "b" are two imaginary values the sort() method uses to determine how to sort an array. Subtracting "b" from "a"  indicates to the sort() method that we want it to sort the array numerically.