3

I see a lot of jQuery examples that do something like

var $element = $('#element');
$element.foo...

rather than just typing

$('#element').foo...

and I do realize there is a small bit of typing saved if you are working with $element a lot, but what about those times that $element is only called once or twice? Why do some developers declare it as a jQuery object variable in those instances? Is it also more efficient for the browser to process?

17
  • 2
    If you're only re-using it once or twice, then no, there's no real improvement at all. Commented Apr 4, 2014 at 21:00
  • 2
    You save maybe 6-7 bytes everytime it's minified, and that's something. Commented Apr 4, 2014 at 21:01
  • 4
    Why do they do it when it's only used once? Who knows. You'd have to ask the developer. Why when only twice? It's a judgement call, and depends on the situation. Is the code in a loop? In a rapidly invoked event handler? Commented Apr 4, 2014 at 21:01
  • 3
    @cookiemonster - while it is a judgment call, re-querying the DOM for the same object twice is not a good judgment. Caching it when it is only used once serves no benefit, but caching it on multiple uses (even as little as two) is always more efficient because it prevents the DOM from being queried multiple times for the same object. Commented Apr 4, 2014 at 21:03
  • 2
    @adeneo - "micro optimization is usually avoided" ... you and i come from very, very different perspectives then. Commented Apr 4, 2014 at 21:38

2 Answers 2

10

Usually this is done to avoid either re-wrapping an element or re-querying the page for the selector.

Such as in a click event

$('.className').click(function(){
 var $this = $(this);
 callSomeHelper($this);
 $this.hide();
 if( $this.data("placement") == "somePlacement" ){
  //some logic
 }
});

The real saver is when it is referencing a set of elements.

var $allSides = $('.side');

And now back in the click event, you can reference this without having to re-query

$('.top').click(function(){
   var door = $allSides.find(':visible');
});

There are obviously more in depth examples, but these two are the main cases that the variable is stored.

Sign up to request clarification or add additional context in comments.

Comments

-3

It prevents from overwriting variable from another script

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.