0

In this code I see the second console.log is called before the one inside the anonymous function.

Is this an example of hoisting? Is it something specific to do with jquery?

var test_var = 'original test_var';

$(document).ready(function() {

    $(function() {

      test_var = 'test_var has been altered!';
      console.log("test_var 1");
      console.log(test_var); //displays 'test_var has been altered!'

    });
    console.log("test_var 2");
    console.log(test_var); //displays 'original test_var'
});
erols
  • 83
  • 2
  • 11
  • 1
    No, the second function call is not hoisted or anything. Rather, the "first" function call *inside the callback* is **deferred**. Welcome to the world of asynchrony! – Bergi Sep 17 '16 at 10:58
  • Not sure this is a duplicate of that function wrapping a function in $() behaves similarly to $(document).ready. Hence it's like adding two handers which are essentially queued. – Brian Sep 17 '16 at 11:05
  • @Brian Sure this is async, what makes you think it isn't? – A. Wolff Sep 17 '16 at 11:06
  • Sorry jumped the gun on that one - is async in the JS sense - maybe not a dupe though. – Brian Sep 17 '16 at 11:08
  • @Brian In dupe, the example `// with promises` is exactly what happen here – A. Wolff Sep 17 '16 at 11:09
  • Yeah can see some similar ones but doesn't really highlight that is't something that may not be clear when using jquery - http://stackoverflow.com/questions/3528509/document-readyfunction-vs-function might be a more appropriate dupe to link to – Brian Sep 17 '16 at 11:12
  • Hahaha... Learn more oop –  Sep 17 '16 at 12:48
  • If I replace `$(function() { ...});` with `(function() { ...})();` the variable is assigned first in the anonymous function and then is not undefined on the next line. Seems that $() is asynchronous. – erols Sep 17 '16 at 20:25

0 Answers0