bug in forloop javascript

Viewed 79

I'm pretty new to webdesign and also to Javascript. While setting up my first web application I run into a bug that I don't understand. It must be something in the way I think Javascript works in webpages or something that I don't know about loops in general.

I'm trying to highlight the best value of a table using js. As long as the file is running locally on my PC, I generate random values and keep pressing the refresh button until a bug occurs. For debugging purposes I also use the console.log function now, but I still don't understand way this is happening...

Many thanks to any hint about what could be wrong in this actually pretty simple code.

// Best value of the week
var table = document.getElementsByTagName('table')[0];
var bestValue = 0;
var bestRow = 0;

for (var i = 1; i < 22; i++) {

   if (table.rows[i].childNodes[5].innerHTML > bestValue){
       bestValue = table.rows[i].childNodes[5].innerHTML;

       console.log(i);
       console.log(table.rows[i].childNodes[5].innerHTML);
       console.log(bestValue);
       bestRow = i;
   }
   else{
       console.log(i);
       console.log(table.rows[i].childNodes[5].innerHTML);
       console.log(bestValue);
   }
}

table.rows[bestRow].childNodes[5].classList.add('bestofweek');

print screen

2 Answers

You are comparing strings, not integers. innerHTML returns string, not a number.

Just add parseInt:

if (parseInt(table.rows[i].childNodes[5].innerHTML) > bestValue){
       bestValue = parseInt(table.rows[i].childNodes[5].innerHTML);

As @AndrewShmig said you are comparing string with int and should use parseInt to convert innerHtml to int first. To explain why not parsing it to int do not work in your case,

in the first iteration:

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

So "6555" > 0 will be true as 6555 > 0, but now you are assigning the bestValue with string "6555" and its no longer an int.

Now subsequent comparisons are between two strings, which are done alphabetically:

"451" > "6555" // false, because 6 comes after 4 alphabetically
"8995" > "6555" // true
"9359" > "8995" // true
// ...
"974" > "9359" // true, because 7 comes after 3 alphabetically
//...

And now you have the wrong value as your max value.

Ref. Javascript comparisons

Related