Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Caching variables programming

What does caching variables mean, like in jQuery I've seen the teacher caching jQuery selectors into a variable and using that variable, does it improve performance?

Hey Akhter Rasool , storing selector in a variable provide you the compatibilty to write code fast . Suppose you have selector like thus $(".name a li") so whenever you need that selector you have to write the whole selector again and again instead of typing selector repeatedly you can do something like this var listItem = $(".name a li"); which is preety suitable that writing complete selector.

1 Answer

The teacher does this for a few reasons. In no particular order, the ones off the top of my head include:

  • It improves the performance of the code a bit, so JavaScript doesn't have to go and look for that element and grab it every time. It just finds it and saves a copy for future operations
  • It's faster for most people to type a variable name than a CSS selector (depending on what they name the variable)
  • If they accidentally misspell something, it'll be easier to catch, because JavaScript (or your text editor's linter) will complain about it, where it might not with a CSS selector in a JavaScript string