QuickTip: Numerical comparisons in JavaScript

This is one of those things I use really rarely, obesity then forget about it and have to re-figure-it-out every time. Never again!

If you are using JavaScript and you have a number inside of a variable as a string, the JS engine won’t do numerical comparisons, so you may get some weird results.

For instance:

var nine = '9'; // the quotes make this a string
var ten = '10';
if(ten > nine){
alert('This makes sense, but will NOT get displayed');
} else {
alert('10 is less than 9 because JS uses a string-comparison ' +
'that stops after it finds the "1" character being '+
'less than the "9" character');
}

… will actually display the second alert. Looks crazy, huh?

To work around this, we can just use arithmetic and subtract the numbers from each other and look at the difference. This chunk of code shows how we can fix this to make more sense:

var nine = '9';
var ten = '10';
if((ten - nine) > 0 ){
alert('This makes more sense!  '+
'Since the difference of the first var minus the '+
'second var is greater than 0, the first var must '+
'be greater than the second.');
} else {
alert('This will NOT be displayed because it would make no sense');
}

Hope that helps someone!

Leave a Reply

Your email address will not be published. Required fields are marked *