0

I have tested something and it was really strange...

When I use:

jQuery(document).ready(function ($){
     console.log($('.box').length);
});

the return value is 4;

If I use this:

 (function ($){
     console.log($('.box').length);
})(jQuery);

the return value is 0;

(in the same document)

Any explanation for that?

(I have tried to reproduce in jsfiddle but both return same value.)

pcurry
  • 1,374
  • 11
  • 23
Jean-philippe Emond
  • 1,619
  • 2
  • 17
  • 29
  • 4
    Well, the first one sets up an event listener, while the second executes immediately? – Bergi Jul 29 '14 at 19:46
  • The reason that the second one is not reproducable in your jsfiddle attempt is probably that you have selected in the fiddle options to wait for DOMready before executing the code (just what the first one does) – Bergi Jul 29 '14 at 19:49
  • thanks for explaination. I suppose that if I move my jquery code at the end.. it will work. – Jean-philippe Emond Jul 29 '14 at 19:51

1 Answers1

1

Your second example will cause the code in the function to run when the whole overall statement is parsed. The jQuery version waits until the DOM has been fully parsed and populated. The two pieces of code are simply different, in other words.

Pointy
  • 405,095
  • 59
  • 585
  • 614