Hope this helps I will try to explain my answer in brief.
The JS runtime executes each piece of code in the execution context. And each execution context has 2 stages :
- Creation Stage: This stage creates all the scopes and variables and functions. Also sets the 'this' context.
- Execution Stage: This stage actually executes the code like
console.log( )
statements by sending machine understandable commands.
Now, when a browser first loads your script, it enters the global execution context by default. This execution context will also have a creation stage and execution stage.
Now considering your code :
//Line 1
var x = doThis();
//Line 2
console.log(x);
//Line 3
function doThis(){
return "Hello World";
}
Here is a pseudo representation of things the interpreter does :
// First Pass
1.Find some code to invoke a function.
2.Before executing the function code, create a context to execute in.
3.Enter the Creation Stage:
- Create a scope chain
- Scan for function declarations
// In your case, this is where *doThis()* is stored in the global scope
- Scan for var declarations
// This is where *var x* is set to *undefined*
4. Run/interpret the function code in the context(Execution Stage)
// Now as per the sequence line 1 will run and set *var x = "Hello World"*
// And then followed by line 2 which will print "Hello World" to console.
This is a just a short overview of what actually happens.I would recommend this article for a detailed insight.
And some references to MDN docs :