# Sorting Javascript Arrays

Use the `sort` function to sort arrays:

``````var animals = ["giraffe", "fish", "toad", "aardvark"];
animals.sort();
// animals is now ["aardvark", "fish", "giraffe", "toad"]
``````

Numerical sort requires a comparator function. You cannot use normal sort because “10” will come before “9”. This is the case even if you specified numbers.

``````var numbers = [20, 10, 30, 9];
numbers.sort();
// numbers is now [10, 20, 30, 9]
``````

Instead, use a comparator function to help sort the array. This function should return a negative, zero, or positive number.

``````var numbers = [20, 10, 30, 9];
numbers.sort(function(a,b) {
return a - b;
});
// numbers is now [9, 10, 20, 30]
``````

# Arrays and Nulls

Below is an example about nulls and arrays

``````  var arrayTest = new Array();
arrayTest = 'hello';
arrayTest = 'bye';
var output = "arrayTest length: " + arrayTest.length;
output += "\n";
output += "0: " + arrayTest;
output += "\n";
output += "1: " + arrayTest;
output += "\n";
if (arrayTest == null) {
output += "arrayTest is null\n";
}
output += "2: " + arrayTest;
output += "\n";
output += "3: " + arrayTest;
output += "\n";
``````

output now holds:

``````arrayTest length: 4
0: hello
1: undefined
arrayTest is null
2: undefined
3: bye
``````