So why are we supposed to cache jQuery objects?
In the following scenario:
var foo = $('#bar');
foo.attr('style','cool');
foo.attr('width','123');
$('#bar').attr('style','cool');
$('#bar').attr('width','123');
Why is the first option so much better than the second option?
If it's because of performance, how does it reduce usage?
Because the jQuery function has a lot of code in it, which involves unnecessary overhead if you execute it more than once with the same inputs expecting the same outputs. By caching the result, you store a reference to the exact element or set of elements you're looking for so you don't have to search the entire DOM again (even if it's a fairly fast search). In many cases (simple pages with small amounts of code) you won't notice a difference, but in the cases where you do it can become a big difference.
You can see this in action by testing your example in jsPerf.
You can also think of it as an example of the Introduce Explaining Variable refactoring pattern for readability purposes, particularly with more complex examples than the one in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With