Just to add to Gaunts answer, cause this one came up for me too.
I was creating a new tbody, and within this tbody I was dynamically creating new rows by looping through an array.
Initially, I had the code loop using the typical for loop which was working fine.
var tableBody = tableBody || document.createElement('tbody')
for (var i = 0, rowCtr = rowOrder.length; i < rowCtr; i++) {
var newRow = tableBody.insertRow(i);
}
But then I went ahead and refactored to use a reverse for loop to reduce the verbosity of that for statement and for the performance advantages at no extra cost to readability and future maintenance.
var tableBody = tableBody || document.createElement('tbody')
for (var i = rowOrder.length; i--;) {
var newRow = tableBody.insertRow(i);
}
Both for loops have the same expected result, with the reverse for loop being more readable. So if rowOrder
is an array of 4 elements, using the reverse for loop will yield this:
start loop
i = 3
i = 2
i = 1
i = 0
end loop
In this loop, the first run through will attempt var newRow = tableBody.insertRow(3)
so you will get an index error because a row at position 0, 1, 2 have not been previously created.
This happened to me on Google Chrome 46.0.2490.80 m - not sure why they thought to throw exceptions on creating a sparse array of rows in the tbody, they can just restructure their code to allow for sparse arrays and then prior to updating the DOM, just re-sort the index keys. Even that is unnecessary, just push the rows out.