0

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!

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
user1783674
  • 65
  • 1
  • 5

2 Answers2

7

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');
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • 1
    dude, `+$(this).attr('data-score1')` will do – naveen Oct 29 '12 at 18:04
  • @webarto that would make it score1 >= score2 – sachleen Oct 29 '12 at 18:05
  • @webarto : there could be a tie – Denys Séguret Oct 29 '12 at 18:05
  • @naveen `parseInt()` is much more readable. If you go for shortness (for some reason), you can use `+` of course. – kapa Oct 29 '12 at 18:07
  • Thank you. No ties are possible so I'll make it else. – user1783674 Oct 29 '12 at 18:14
  • @bažmegakapa: whats readable? a unary plus or parsing int with base 10? – naveen Oct 29 '12 at 18:30
  • @naveen .. Unary plus can be very useful.. But many people do not know about that operator.. So I think he says parseint is more readable in this case.. I don't think one who has no idea about parseInt to have an idea about unary plus.. – Sushanth -- Oct 29 '12 at 18:31
  • 2
    @naveen You might or might not know that in Javascript unary `+` converts to number. If you see `parseInt()`, you already know what it does. If not, you have a function name to search on. I mean, yes, it is very clever that you know this trick, but do you really want to use it in code that other people will read? – kapa Oct 29 '12 at 18:33
3

You're comparing the values as strings. The string "90" begins with 9, which has an ascii code that is greater than that of 1.

You can convert it to a number by using parseInt

parseInt(score1, 10)
sachleen
  • 30,730
  • 8
  • 78
  • 73