A little code review
The review
The review was based on some javascript (jQuery) code that i wrote to handle disabling of inputs in a form, basing on user actions.
I will list the remarks I've got from my colleagues, no code, just what they've said, after that I will add some thoughts.
My colleagues remarks
- It's a good practice to cache elements into variables, so that the process of finding them is done only once
- window.confirm and window.alert are functions invoked on a global object so they can be called just by invoking the function by itself
- jQuery offers a chaining functionality that permits to call subsequent functions one right after the other
- it is possible to limit the portion of code in which jQuery searches for an element with the following: $('.someInput', '#thatInputContainer')...
- prefer loops over calling each(function(){}) because of the function call that get called on every item
My thoughts
I wasn't sure about that last statement, so I've put up a little test, see the results by opening it with Firefox, clicking on the console tab and then on Persist, the timings should appear in the box right under. If you run it it turns out that to perform the first two operations (I had a similar case in my code) it only takes around 4ms, this is faster enough in my case so I'll go the each way, also gaining the benefit of having a function that limits my namespace.
The second example, which I've took from here shows the timings with array accessing. This time things go differently but I believe it's because of the array access times, not because of the each, so I'll just use each everytime since I did not find any evidence of the fact that it is slower. Or at least it is not slower in a measure in which my code is affected by it, for now :P
Feel free to post your experience on this subject, especially if I'm wrong ;D
Oh... and as I'm on it: have a look at jQuery tips and tricks on stackoverflow.