0

Here is Pseudo-code of jQuery

$(document).ready(function(){
   printHelloworld(); 
});    
var printHelloworld = function(){
   console.log('hello world');
}

In this sample, the console will print hello world.

My question is that Function expression must be assigned before usage, but in this sample, I used the printHelloworld() before assigned it. I do not know what have .ready() function done? Did it do something to hoist the function?

2
  • As the name suggests the document ready function will run when the document is ready. By that time it has access to printHelloworld as this is declared globally. Please check learn.jquery.com/using-jquery-core/document-ready Commented Jun 17, 2016 at 1:59
  • this function is delcared after but it work cause ready function only work after all document is loaded Commented Jun 17, 2016 at 2:06

1 Answer 1

0

The var hoisted the printHelloworld function declaration to the top of the function (or script). It wasn't initialized until you assigned it after your $(document).ready() statement, but the anonymous function you passed to ready still held a reference to the variable. By the time the function executed, the printHelloworld variable was initialized and usable.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.