I'm an advocate for vanilla JS. But jQuery is still used on millions of websites, so it's worth discussing how to optimise it. One problem I often see is that developers don't cache their jQuery selections, even though they're using them in multiple places. I'll show you what I mean.

Vanilla JS

In vanilla JS, if I were going to (for example) get all the h2 elements on the page, I would save the selection to a variable. That way, if I needed to use it in more than one place, I wouldn't need to keep re-selecting the elements every time. It would look something like this:

// Get all h2 elements as an array
const headings = [...document.querySelectorAll('h2')];

// Early in the script...
headings.forEach(heading => heading.classList.add('text-large'));


//
// (a bunch more code)
//


// Later in the script...
headings.forEach(heading => heading.classList.remove('text-large'));

jQuery: The wrong way

In jQuery, I often see people do this, which you should NOT do:

// Early in the script...
$('h2').addClass('text-large');


//
// (a bunch more code)
//


// Later in the script...
$('h2').removeClass('text-large');

This constructs the same jQuery object twice. Why create extra work for the browser when you could just cache the return value?

jQuery: The right way

You should save the selection to a variable, just like you would in vanilla JS:

// Get all h2 elements as a jQuery object
const $headings = $('h2');

// Early in the script...
$headings.addClass('text-large');


//
// (a bunch more code)
//


// Later in the script...
$headings.removeClass('text-large');

This might seem like a minor thing—and in a small codebase, it probably is—but little performance issues like this can add up and have a meaningful impact. It's also just not very DRY to keep making the same selections over and over again. We all want to write better software, don't we? So little tips like this are a no-brainer for me.