0

I wondered what the difference of using jQuery or not using it might be considering the following task. I have not found any answer yet.

jQuery:

jQuery(function() { alert("Hello World!"); })
$(function() { alert("Hello World!"); })

Pure JavaScript:

(function() { alert("Hello World!"); })()

What is the difference? When should I use which approach? Thank you!

2
  • There is no difference in the two first examples, one references jQuery, the other references the aliased $, which is the same as jQuery, both waits for the DOM to be ready. The third one is pretty much the same but without jQuery, and executes immediately, and I'm not sure I get the question, as the difference should be rather obvious ? Commented Nov 7, 2013 at 22:02
  • Yes, that is rather obvious. Nonetheless, the question remained whether there is a difference in the way they are executed. I already noticed that using jQuery returns an object while the pure JavaScript solution returns undefined. Commented Nov 7, 2013 at 22:06

4 Answers 4

4

In general, $(function() { alert("Hello World!"); }) waits for $(document).ready() and the other function (an IIFE) fires immediately.

BUT the jQuery wrapped function is a very-specific use case (waiting for the DOM, using jQuery); your two examples are otherwise unrelated. Don't confuse them as 2 versions of the same thing.

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

Comments

0
$(function(){
  alert("hello world");
});

is short hand for:

$(document).ready(function(){
    alert("hello world");
});

so it will be executed after DOM loads.

while you pure js will be executed before DOM loads.

Comments

0

The jQuery version binds to be executed once the DOM loads. The kind in just a closure executes as soon as it's defined. So if you want it to execute immediately, use the second version, if it should wait until everything's loaded, use the first.

At least, that's what I've got off the top of my head.

Comments

0

The main difference is that the jQuery functions are executed after the DOM is loaded. And the pure JavaScript lambda function is executed immediately (within its context).

The second jQuery function is shorthand for the first.

You could still put the JavaScript lambda function inside the jQuery wrapper. This would mean that the lambda function would execute right after the DOM has loaded (thanks to jQuery taking care of that).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.