0

I have this below function in my project:-

function RowSelection() {
  var table = document.getElementById("tbl_Audit");
  if (table != null) {
    for (var x = 0; x < table.rows.length; x++) {
      for (var j = 0; j < table.rows[x].cells.length; j++) {
        if (j = 4) {
          alert("condition passed " + j)
          table.rows[x].cells[j].onclick = function() {
            tableText(this);
          }
        }
      }
    }
  }
}

when this function is triggered it goes into a never ending loop. Can anybody please help me identify what I am doing wrong here.

3
  • Console log the table.rows.length; What's the count ? And also table.rows[x].cells.length whats the count ? Commented Oct 28, 2016 at 22:26
  • 2
    = is assignment, == and === are comparison Commented Oct 28, 2016 at 22:28
  • Dupe of stackoverflow.com/questions/36460244/… Commented Oct 28, 2016 at 22:29

1 Answer 1

4

Change if (j=4) to if (j===4).

= is an assignment, which isn't a syntax error so the code runs, but it changes the value of j to 4, so (assuming 4 is less than the number of cells) your loop condition will always be true.

Sign up to request clarification or add additional context in comments.

4 Comments

Hmm, that's right. But can that cause never ending loop ?
@Nandan - Sure, because j is the inner loop's counter.
Okay, But what I thought was, for every iteration, the if block should be executed right? So if the table.rows[x].cells.length value is 1000 (just example) it should show alert for 1000*outer loop count. Isn't it ?
@Nandan - At the end of every iteration of the inner loop, j will be incremented by the j++ of the for, but then the if (j=4) will change j back to 4. So every time (after the first) that the inner loop condition is evaluated j will be 5. If that is less than table.rows[x].cells.length then the inner loop condition will always be true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.