5

So in interpreted language, like javascript, we have:

var x = doThis(); // function call, assign statement

console.log(x); // print statement

function doThis(){ //function declaration
 return "Hello World"; //return statement
}

And my question is:

When in time(runtime) does the print statement actually gets executed? Before or after the function declaration gets parsed? And if it gets executed before, how, because there is no compiler, and code gets immediately executed.

P.S I have read something about function hoisting but still do not understand it.

damitj07
  • 2,689
  • 1
  • 21
  • 40
  • 3
    Hoisting means that declared variables and functions are placed in memory in a first parsing run, then the code is executed. So that function is effectively "hoisted to the top" and is available as the code is executed. https://jsfiddle.net/bsp38yc9/ – Jared Farrish Mar 18 '18 at 13:27
  • Also see the difference with [IIF's](https://jsfiddle.net/bsp38yc9/5/). – Jared Farrish Mar 18 '18 at 13:32
  • "Hoisted to the top of the scope". Also see [variable shadowing](https://stackoverflow.com/questions/11901427/an-example-of-variable-shadowing-in-javascript). – Jared Farrish Mar 18 '18 at 14:13

1 Answers1

5

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 :

damitj07
  • 2,689
  • 1
  • 21
  • 40