0

I am posting this as I study deeper into both JavaScript and jQuery. The following code

$(function () { 
    alert('instance');
});

$(alert('hi'));

alerts "hi" and "instance" in that order! I'm sure there is an understanding into how js thinks on this because I would think it would be "instance" and "hi" - can anyone explain this? Thanks

0

3 Answers 3

2

$(function() { ... }) is an alias for $(document).ready(function() { ... })

Your second is sort of nonsensical and evaluates something like this:

alert 'hi', then create a jquery object of the return value (I believe undefined)

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

1 Comment

thank you, the fact that $(something) === $(document).ready(something) is what I needed to know
0

$(function(){}) is a shortcut for $(document).ready(function(){}) which means the execution of code inside $(function(){}) will be delayed till the document is completely loaded.

The code execution sequence here will be something like

  1. $(function(){}) gets executed resulting in registering a document ready callback
  2. $(alert('hi')); gets executed, here alert('hi') gets executed resulting in the popup and it returns a undefined value to jQuery which will ignore it.
  3. the document ready event is fired resulting the execution of the registered callback ie alert with instance

The difference between the code is in the first case you are not immediatly executing the function, you are passing the function as a parameter to jQuery (because there is no () after the function definition). In the second case you are calling alert('hi') which will result in calling the alert immediately and then passing the returned value of alert to jQuery

1 Comment

I believe the part he's missing is that his second call to $() is being passed the result of an alert.
0

When you do

$(function () { 
    alert('instance');
});

, a function is created that will alert "instance", then the function is passed to jQuery ($). JQuery remembers the function, and calls the function when the DOM tree is loaded. This is an alias for $(document).ready(function(){...}).

When you do

$(alert('hi'));

alert('hi') is called immediately, and the return value will be passed to jQuery. Chances are "immediately" occurs before "when the DOM tree is loaded".

Everywhere I've tested, alert returns undefined. Passing undefined to jQuery has no observable effect as far as I can tell.

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.