Why cache jQuery objects?

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.

Leave a Comment