Thursday, June 12, 2014

debuggin' and safe js iterators

I just spend like a whole work day digging through a sampload of datatables code to find this issue... I finally tracked it down to some datatable wrapper/filter code we had that was iterating over an array like this:

for(var i in arrayOfFilterFunctions) {
//...
}

The trouble is, the "legacy" page the datatables widget was on included "prototype.js", and prototype adds an each function (ironically enough, for iterating) and that meant arrayOfFilterFunctions["each"] was a function that could be called, and was returning undefined, which were false-y enough to "filter out" the rows I was trying to add.

for(var i = 0; i < someArray; i++) {
//...
}

is clunky, but safer for reasons like this. (9 times out of 10 either will work, but that 1 in 10 can be a doozy, case in point my last day at work) Also, personally, I always subconsciously expect

for(var thing in someMap) {
//...
}

to set thing to the array entry, but of course you have to do something like

for(var key in someMap){
    var thing = someMap[key];
//...
}

Some people think this is a strong argument for CoffeeScript and other preprocessed variants of javascript that let you write syntactically sweeter code than "raw JS", but I don't think that sweetness makes up for the disconnect between the code the coder writes and the code the coder looks at in the debugger window / what the browser is actually running.

No comments:

Post a Comment