-2

I'm curious the different between

$('#btn').click(function(e) {
    e.preventDefault();
    //do sth
});

Note : $('#btn')


and this : I store my selector into a variable and re-use.

$btn = $('#btn');
$btn.click(function(e) {
    e.preventDefault();
    //do sth
});

Note : $btn


Now imagine, if I have do 1000 times of these in my file, which one is better to do and why ?

code-8
  • 54,650
  • 106
  • 352
  • 604
  • Please search before asking. This is a very frequent question. – Denys Séguret May 05 '15 at 13:55
  • @dystroy: Thanks for the downvote and mark my post as duplicate, but I disagree with you. I think my question is precisely short, get to the point, and neat, and very easy to understand. I'm sure some people will like this post than the one you suggested. – code-8 May 05 '15 at 13:59
  • @rangerover.js If you think your question (and its answers) are sufficiently better than the previous question, you can try to turn this question into a canonical. For something this simple and well-resolved, though, that will probably be difficult to get people on-board with. – ssube May 05 '15 at 14:01
  • Do you know that `$` is just a function? Do you think it's better to call a function 1000 times than not? – Florian Margaine May 05 '15 at 14:01

2 Answers2

1

Now imagine, if I have do 1000 times of these in my file, which one is better to do and why ?

which one is better:

The second approach.

Why:

In case of first approach, $('#btn') will look for the element in html everytime you use it. Whereas in second case it has already fetched the object stored in variable and don't look for the element in DOM again.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

If you have to use the same selector more than once you should store this selector to a variable and use it multiple times.

On the other hand, there is no reason to store a selector to a variable if you are going to use it only once.

For example:

$('table tr').each(function() {
   // Store the $(this) object to a variable in order to use it multiple times
   var that = $(this);
   var id = that.attr('id');
   that.attr('title', 'this row has id: ' + id);
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61
  • You don't need to give me an example. I got you at the first place. Keep your answer minimum and clean. – code-8 May 05 '15 at 14:01
  • I disagree: you should only store the result of the selection if it's not going to change. See Milind Anatwar's answer. – JotaBe May 05 '15 at 14:07