Variable caching in with jQuery is a way to keep your element references so you don’t have to do continues look ups.
There are times you want to use this and other times you don’t.

One thing to keep in mind is what scope you create your cache var on, if it’s going to be global scope you’re setting yourself up so that cache happens only once.
Another way to cache is before doing a loop, so you can use the cache element reference in the loop without triggering additional lookups again for the same element(s).

You gain significant performance by doing this correctly.

If you want to test this out and measure something let’s create a quick demo and see if we can measure the difference as well as see how caching can help.

<div class="awesome-container">Awesome Container 1</div>
<div class="awesome-container">Awesome Container 2</div>
<div class="awesome-container">Awesome Container 3</div>
<div class="awesome-container">Awesome Container 4</div>
<div class="awesome-container">Awesome Container 5</div>
<div class="awesome-container">Awesome Container 6</div>
<div class="awesome-container">Awesome Container 7</div>
<div class="awesome-container">Awesome Container 8</div>
<div class="awesome-container">Awesome Container 9</div>
<div class="awesome-container">Awesome Container 10</div>

We’ll create 10 awesome containers with the text awesome container inside. Our goal will be to loop through 1 to 1000 inserting a div in each of these containers. We’ll measure the difference when using the normal lookup $('awesome-container') and using the cache to do the same process.

var $awesomeContainer = $(".awesome-container")
var arrayOneToOneHundred = [...new Array(100)].map((a, i) => i + 1) // shorthand to create an array with 1 to 100.
 
// Test 1
 
;[1, 2, 3, 4].forEach((item) => $awesomeContainer.appendChild("<div>" + item + "</div>"))

I’ve created a demo which showcases all the performance impact of caching a reference element. It’s an extreme case however it does highlight even on a most basic level a performance gain. When we multiply this over the scope of a whole project this could result in significant performance impact.

https://codepen.io/jessycormier/pen/mdKGQxM