Main Page


The highlighted block of code contains an
statement testing which array has more items (if they are
equal, no changes are necessary). Both branches of the
statement do the same thing on different
arrays: The first adds zeroes to
, whereas the second adds zeroes to
. After this
point, both arrays have an equal number of digits.
The final step is to iterate through the arrays and compare the corresponding digits in each array:
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = sVersion1.split(“.”);
var aVersion2 = sVersion2.split(“.”);
if (aVersion1.length > aVersion2.length) {
for (var i=0; i < aVersion1.length - aVersion2.length; i++) {
} else if (aVersion1.length < aVersion2.length) {
for (var i=0; i < aVersion2.length - aVersion1.length; i++) {
for (var i=0; i < aVersion1.length; i++) {
if (aVersion1[i] < aVersion2[i]) {
return -1;
} else if (aVersion1[i] > aVersion2[i]) {
return 1;
return 0;
In this section, a
loop is used to compare the arrays. If a digit in
is less than the corre-
sponding digit in
, the function automatically exits and returns –1. Likewise, if the digit in
is greater than the one from
, the function exits and returns 1. If all digits are
tested and no value has been returned, the function returns 0, meaning that the two versions are equal.
This function is used like this:
alert(compareVersions(“0.9.2”, “0.9”)); //returns 1
alert(compareVersions(“1.13.2”, “1.14”)); //returns –1
alert(compareVersions(“5.5”, “5.5”)); //returns 0
The first line returns 1 because 0.9.2 is greater than 0.9; the second line returns –1, because 1.13.2 is less
than 1.14; the third line returns 0 because the two versions are equal. This function is used extensively in
this chapter.
Chapter 8
11_579088 ch08.qxd 3/28/05 11:38 AM Page 236

JavaScript EditorFree JavaScript Editor     Ajax Editor