user1783674 user1783674 - 3 months ago 9
Javascript Question

Comparing numbers in javascript

So here's my code:

var score1 = $(this).attr('data-score1');
var score2 = $(this).attr('data-score2');

if (score1 < score2) {
// do some
}
if (score2 > score1) {
// do something else
}


Now, this works fine as long as both variables are either both < or both > 100, yet whenever either of those variable is larger than 100 while the other is not the wrong if statement gets triggered. What the hell could be going on here?
Thanks for any advice!

Answer

Use parseInt()

The attributes will throw up strings.. So when you try to compare them... You are actually comparing

"100" > "90" and not 100 > 90 .. Using parseInt() with a radix should solve your problem..

var score1 = parseInt( $(this).attr('data-score1') , 10);
var score2 = parseInt( $(this).attr('data-score2') , 10);

if (score1 < score2) {
  // do some
}
else if (score2 > score1) {
  // do something else
}

As @naveen suggested you could do this as well

var score1 = +$(this).attr('data-score1');
var score2 = +$(this).attr('data-score2');