Search code examples
javascriptcomparisonstring-comparison

Comparing 1.3.52 and 1.3.54 as strings and as numbers


I am wondering why the following works:

oldversion = "1.3.52";
newversion = "1.3.54";

if (newversion > oldversion) {
    console.log('test');
}

but this does not:

if (1.3.54 > 1.3.52) {
    console.log('test');
}

I know that the last example won't work because they are not actual numbers. But I am trying to find out what JavaScript is doing when it encounters a string with a number in it.

This is what I found on W3Schools' JavaScript Comparison and Logical Operators page:

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.

So how come it converts the string to a number and suddenly I am not getting an Uncaught SyntaxError: Unexpected number anymore?


Solution

  • You could use a function which iterates the segments.

    function checkVersion(a, b) {
        var aa = a.split('.').map(Number),
            bb = b.split('.').map(Number),
            i,
            r = 0,
            l = Math.max(aa.length, bb.length);
    
        for (i = 0; !r && i < l; i++) {
            r = (aa[i] || 0) - (bb[i] || 0);
        }
        return r;
    }
    
    var oldversion = "1.3.52",
        newversion = "1.3.54";
    
    if (checkVersion(newversion, oldversion) > 0) {
        console.log('test');
    }